2019-12-02 00:42:40 +01:00
|
|
|
/*
|
|
|
|
This file is part of GNU Taler
|
2022-03-08 23:09:20 +01:00
|
|
|
(C) 2019-2022 Taler Systems S.A.
|
2019-12-02 00:42:40 +01:00
|
|
|
|
|
|
|
GNU 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.
|
|
|
|
|
|
|
|
GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
|
|
|
|
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
|
|
|
|
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
|
|
|
|
|
|
|
You should have received a copy of the GNU General Public License along with
|
|
|
|
GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
|
|
|
|
*/
|
|
|
|
|
2019-12-15 19:04:14 +01:00
|
|
|
/**
|
|
|
|
* Implementation of the payment operation, including downloading and
|
|
|
|
* claiming of proposals.
|
|
|
|
*
|
|
|
|
* @author Florian Dold
|
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Imports.
|
|
|
|
*/
|
2022-09-16 16:24:47 +02:00
|
|
|
import { GlobalIDB } from "@gnu-taler/idb-bridge";
|
2021-03-27 19:35:44 +01:00
|
|
|
import {
|
2022-10-08 20:56:57 +02:00
|
|
|
AbortingCoin,
|
|
|
|
AbortRequest,
|
2022-03-22 21:16:38 +01:00
|
|
|
AbsoluteTime,
|
2022-09-15 20:16:42 +02:00
|
|
|
AgeRestriction,
|
2021-03-27 19:35:44 +01:00
|
|
|
AmountJson,
|
2022-03-08 23:09:20 +01:00
|
|
|
Amounts,
|
2022-10-08 20:56:57 +02:00
|
|
|
ApplyRefundResponse,
|
|
|
|
codecForAbortResponse,
|
2022-11-08 17:00:34 +01:00
|
|
|
codecForMerchantContractTerms,
|
2022-10-08 20:56:57 +02:00
|
|
|
codecForMerchantOrderRefundPickupResponse,
|
|
|
|
codecForMerchantOrderStatusPaid,
|
2022-03-08 23:09:20 +01:00
|
|
|
codecForMerchantPayResponse,
|
|
|
|
codecForProposal,
|
|
|
|
CoinDepositPermission,
|
2022-10-15 11:52:07 +02:00
|
|
|
CoinRefreshRequest,
|
|
|
|
CoinStatus,
|
2022-03-08 23:09:20 +01:00
|
|
|
ConfirmPayResult,
|
|
|
|
ConfirmPayResultType,
|
2022-11-01 11:34:20 +01:00
|
|
|
MerchantContractTerms,
|
2022-07-12 17:41:14 +02:00
|
|
|
ContractTermsUtil,
|
2022-09-15 20:16:42 +02:00
|
|
|
DenominationInfo,
|
2022-03-08 23:09:20 +01:00
|
|
|
Duration,
|
|
|
|
encodeCrock,
|
2022-06-10 13:03:47 +02:00
|
|
|
ForcedCoinSel,
|
2022-03-08 23:09:20 +01:00
|
|
|
getRandomBytes,
|
|
|
|
HttpStatusCode,
|
|
|
|
j2s,
|
|
|
|
Logger,
|
2022-10-08 20:56:57 +02:00
|
|
|
MerchantCoinRefundFailureStatus,
|
|
|
|
MerchantCoinRefundStatus,
|
|
|
|
MerchantCoinRefundSuccessStatus,
|
2022-03-08 23:09:20 +01:00
|
|
|
NotificationType,
|
2022-09-19 11:28:47 +02:00
|
|
|
parsePaytoUri,
|
2022-03-08 23:09:20 +01:00
|
|
|
parsePayUri,
|
2022-10-08 20:56:57 +02:00
|
|
|
parseRefundUri,
|
2022-06-10 13:03:47 +02:00
|
|
|
PayCoinSelection,
|
2022-03-08 23:09:20 +01:00
|
|
|
PreparePayResult,
|
|
|
|
PreparePayResultType,
|
2022-10-08 20:56:57 +02:00
|
|
|
PrepareRefundResult,
|
2022-03-08 23:09:20 +01:00
|
|
|
RefreshReason,
|
2022-09-15 20:16:42 +02:00
|
|
|
strcmp,
|
2022-03-08 23:09:20 +01:00
|
|
|
TalerErrorCode,
|
2022-03-22 21:16:38 +01:00
|
|
|
TalerErrorDetail,
|
2022-03-18 15:32:41 +01:00
|
|
|
TalerProtocolTimestamp,
|
2022-03-22 21:16:38 +01:00
|
|
|
TransactionType,
|
|
|
|
URL,
|
2022-11-25 03:16:01 +01:00
|
|
|
constructPayUri,
|
2023-01-05 18:45:49 +01:00
|
|
|
PayMerchantInsufficientBalanceDetails,
|
2021-03-27 19:35:44 +01:00
|
|
|
} from "@gnu-taler/taler-util";
|
2022-09-05 18:12:30 +02:00
|
|
|
import { EddsaKeypair } from "../crypto/cryptoImplementation.js";
|
2021-06-14 16:08:58 +02:00
|
|
|
import {
|
|
|
|
AllowedAuditorInfo,
|
|
|
|
AllowedExchangeInfo,
|
2021-06-25 13:27:06 +02:00
|
|
|
BackupProviderStateTag,
|
2021-06-14 16:08:58 +02:00
|
|
|
CoinRecord,
|
|
|
|
DenominationRecord,
|
|
|
|
PurchaseRecord,
|
2022-10-14 22:38:40 +02:00
|
|
|
PurchaseStatus,
|
2022-10-08 20:56:57 +02:00
|
|
|
RefundReason,
|
|
|
|
RefundState,
|
2021-06-14 16:08:58 +02:00
|
|
|
WalletContractData,
|
2022-10-08 20:56:57 +02:00
|
|
|
WalletStoresV1,
|
2021-06-14 16:08:58 +02:00
|
|
|
} from "../db.js";
|
2022-01-16 21:47:43 +01:00
|
|
|
import {
|
2022-03-22 21:16:38 +01:00
|
|
|
makeErrorDetail,
|
|
|
|
makePendingOperationFailedError,
|
|
|
|
TalerError,
|
2022-09-21 12:40:02 +02:00
|
|
|
TalerProtocolViolationError,
|
2022-01-16 21:47:43 +01:00
|
|
|
} from "../errors.js";
|
2022-10-08 20:56:57 +02:00
|
|
|
import { GetReadWriteAccess } from "../index.browser.js";
|
2022-09-05 18:12:30 +02:00
|
|
|
import {
|
|
|
|
EXCHANGE_COINS_LOCK,
|
|
|
|
InternalWalletState,
|
|
|
|
} from "../internal-wallet-state.js";
|
2022-09-19 12:13:31 +02:00
|
|
|
import { PendingTaskType } from "../pending-types.js";
|
2022-09-05 18:12:30 +02:00
|
|
|
import { assertUnreachable } from "../util/assertUnreachable.js";
|
2022-01-16 21:47:43 +01:00
|
|
|
import {
|
2022-09-15 20:16:42 +02:00
|
|
|
CoinSelectionTally,
|
2022-03-08 23:09:20 +01:00
|
|
|
PreviousPayCoins,
|
2022-09-15 20:16:42 +02:00
|
|
|
tallyFees,
|
2022-01-16 21:47:43 +01:00
|
|
|
} from "../util/coinSelection.js";
|
2021-06-14 16:08:58 +02:00
|
|
|
import {
|
|
|
|
getHttpResponseErrorDetails,
|
|
|
|
readSuccessResponseJsonOrErrorCode,
|
|
|
|
readSuccessResponseJsonOrThrow,
|
|
|
|
readTalerErrorResponse,
|
2021-08-24 15:08:34 +02:00
|
|
|
readUnexpectedResponseDetails,
|
2022-03-08 23:09:20 +01:00
|
|
|
throwUnexpectedRequestError,
|
2021-06-14 16:08:58 +02:00
|
|
|
} from "../util/http.js";
|
2022-09-16 16:20:47 +02:00
|
|
|
import { checkDbInvariant, checkLogicInvariant } from "../util/invariants.js";
|
2022-09-16 19:27:24 +02:00
|
|
|
import {
|
|
|
|
OperationAttemptResult,
|
|
|
|
OperationAttemptResultType,
|
|
|
|
RetryInfo,
|
|
|
|
RetryTags,
|
|
|
|
scheduleRetry,
|
|
|
|
} from "../util/retries.js";
|
2022-09-19 12:13:31 +02:00
|
|
|
import {
|
2022-10-14 22:47:11 +02:00
|
|
|
makeTransactionId,
|
2022-09-19 12:13:31 +02:00
|
|
|
spendCoins,
|
2022-10-08 20:56:57 +02:00
|
|
|
storeOperationError,
|
2022-10-14 22:38:40 +02:00
|
|
|
storeOperationPending,
|
2022-10-08 20:56:57 +02:00
|
|
|
} from "./common.js";
|
2022-01-16 21:47:43 +01:00
|
|
|
import { getExchangeDetails } from "./exchanges.js";
|
2022-10-08 20:56:57 +02:00
|
|
|
import { createRefreshGroup, getTotalRefreshCost } from "./refresh.js";
|
2022-10-21 15:11:41 +02:00
|
|
|
import { GetReadOnlyAccess } from "../util/query.js";
|
2023-01-05 18:45:49 +01:00
|
|
|
import { getMerchantPaymentBalanceDetails } from "./balance.js";
|
2019-12-02 00:42:40 +01:00
|
|
|
|
2019-12-25 21:47:57 +01:00
|
|
|
/**
|
|
|
|
* Logger.
|
|
|
|
*/
|
2023-01-05 18:45:49 +01:00
|
|
|
const logger = new Logger("pay-merchant.ts");
|
2019-12-25 21:47:57 +01:00
|
|
|
|
2019-12-02 00:42:40 +01:00
|
|
|
/**
|
2019-12-25 19:11:20 +01:00
|
|
|
* Compute the total cost of a payment to the customer.
|
2020-03-30 12:39:32 +02:00
|
|
|
*
|
2019-12-25 21:47:57 +01:00
|
|
|
* This includes the amount taken by the merchant, fees (wire/deposit) contributed
|
|
|
|
* by the customer, refreshing fees, fees for withdraw-after-refresh and "trimmings"
|
|
|
|
* of coins that are too small to spend.
|
2019-12-25 19:11:20 +01:00
|
|
|
*/
|
|
|
|
export async function getTotalPaymentCost(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
pcs: PayCoinSelection,
|
2020-09-08 17:15:33 +02:00
|
|
|
): Promise<AmountJson> {
|
2021-06-09 15:14:17 +02:00
|
|
|
return ws.db
|
2022-09-13 13:25:41 +02:00
|
|
|
.mktx((x) => [x.coins, x.denominations])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadOnly(async (tx) => {
|
2022-03-23 18:20:18 +01:00
|
|
|
const costs: AmountJson[] = [];
|
2021-06-09 15:14:17 +02:00
|
|
|
for (let i = 0; i < pcs.coinPubs.length; i++) {
|
|
|
|
const coin = await tx.coins.get(pcs.coinPubs[i]);
|
|
|
|
if (!coin) {
|
|
|
|
throw Error("can't calculate payment cost, coin not found");
|
|
|
|
}
|
|
|
|
const denom = await tx.denominations.get([
|
|
|
|
coin.exchangeBaseUrl,
|
|
|
|
coin.denomPubHash,
|
|
|
|
]);
|
|
|
|
if (!denom) {
|
|
|
|
throw Error(
|
|
|
|
"can't calculate payment cost, denomination for coin not found",
|
|
|
|
);
|
|
|
|
}
|
|
|
|
const allDenoms = await tx.denominations.indexes.byExchangeBaseUrl
|
2021-12-01 18:07:55 +01:00
|
|
|
.iter(coin.exchangeBaseUrl)
|
|
|
|
.filter((x) =>
|
2022-09-14 21:27:03 +02:00
|
|
|
Amounts.isSameCurrency(
|
|
|
|
DenominationRecord.getValue(x),
|
|
|
|
pcs.coinContributions[i],
|
|
|
|
),
|
2021-12-01 18:07:55 +01:00
|
|
|
);
|
2022-01-13 22:01:14 +01:00
|
|
|
const amountLeft = Amounts.sub(
|
2022-09-14 21:27:03 +02:00
|
|
|
DenominationRecord.getValue(denom),
|
2022-01-13 22:01:14 +01:00
|
|
|
pcs.coinContributions[i],
|
|
|
|
).amount;
|
2022-09-14 21:27:03 +02:00
|
|
|
const refreshCost = getTotalRefreshCost(
|
|
|
|
allDenoms,
|
|
|
|
DenominationRecord.toDenomInfo(denom),
|
|
|
|
amountLeft,
|
|
|
|
);
|
2022-11-02 17:42:14 +01:00
|
|
|
costs.push(Amounts.parseOrThrow(pcs.coinContributions[i]));
|
2021-06-09 15:14:17 +02:00
|
|
|
costs.push(refreshCost);
|
|
|
|
}
|
2022-11-02 17:42:14 +01:00
|
|
|
const zero = Amounts.zeroOfAmount(pcs.paymentAmount);
|
2021-07-12 15:55:31 +02:00
|
|
|
return Amounts.sum([zero, ...costs]).amount;
|
2021-06-09 15:14:17 +02:00
|
|
|
});
|
2019-12-25 19:11:20 +01:00
|
|
|
}
|
|
|
|
|
2020-11-03 17:39:30 +01:00
|
|
|
async function failProposalPermanently(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
proposalId: string,
|
2022-03-22 21:16:38 +01:00
|
|
|
err: TalerErrorDetail,
|
2020-11-03 17:39:30 +01:00
|
|
|
): Promise<void> {
|
2021-06-09 15:14:17 +02:00
|
|
|
await ws.db
|
2022-10-08 20:56:57 +02:00
|
|
|
.mktx((x) => [x.purchases])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadWrite(async (tx) => {
|
2022-10-08 20:56:57 +02:00
|
|
|
const p = await tx.purchases.get(proposalId);
|
2021-06-09 15:14:17 +02:00
|
|
|
if (!p) {
|
|
|
|
return;
|
|
|
|
}
|
2022-10-08 23:45:49 +02:00
|
|
|
p.purchaseStatus = PurchaseStatus.ProposalDownloadFailed;
|
2022-10-08 20:56:57 +02:00
|
|
|
await tx.purchases.put(p);
|
2021-06-09 15:14:17 +02:00
|
|
|
});
|
2020-11-03 17:39:30 +01:00
|
|
|
}
|
|
|
|
|
2022-09-05 18:12:30 +02:00
|
|
|
function getProposalRequestTimeout(retryInfo?: RetryInfo): Duration {
|
2022-05-19 10:36:01 +02:00
|
|
|
return Duration.clamp({
|
2022-05-19 11:01:07 +02:00
|
|
|
lower: Duration.fromSpec({ seconds: 1 }),
|
|
|
|
upper: Duration.fromSpec({ seconds: 60 }),
|
2022-09-05 18:12:30 +02:00
|
|
|
value: retryInfo ? RetryInfo.getDuration(retryInfo) : Duration.fromSpec({}),
|
2022-05-19 10:36:01 +02:00
|
|
|
});
|
2020-08-20 12:57:20 +02:00
|
|
|
}
|
|
|
|
|
2020-09-07 12:24:22 +02:00
|
|
|
function getPayRequestTimeout(purchase: PurchaseRecord): Duration {
|
2022-09-05 18:12:30 +02:00
|
|
|
return Duration.multiply(
|
2021-02-05 12:10:56 +01:00
|
|
|
{ d_ms: 15000 },
|
2022-10-08 20:56:57 +02:00
|
|
|
1 + (purchase.payInfo?.payCoinSelection.coinPubs.length ?? 0) / 5,
|
2020-09-08 22:48:03 +02:00
|
|
|
);
|
2020-08-20 12:57:20 +02:00
|
|
|
}
|
|
|
|
|
2022-10-08 20:56:57 +02:00
|
|
|
/**
|
|
|
|
* Return the proposal download data for a purchase, throw if not available.
|
|
|
|
*
|
|
|
|
* (Async since in the future this will query the DB.)
|
|
|
|
*/
|
|
|
|
export async function expectProposalDownload(
|
2022-10-09 02:23:06 +02:00
|
|
|
ws: InternalWalletState,
|
2022-10-08 20:56:57 +02:00
|
|
|
p: PurchaseRecord,
|
2022-10-21 15:11:41 +02:00
|
|
|
parentTx?: GetReadOnlyAccess<{
|
|
|
|
contractTerms: typeof WalletStoresV1.contractTerms;
|
|
|
|
}>,
|
2022-10-09 02:23:06 +02:00
|
|
|
): Promise<{
|
|
|
|
contractData: WalletContractData;
|
|
|
|
contractTermsRaw: any;
|
|
|
|
}> {
|
2022-10-08 20:56:57 +02:00
|
|
|
if (!p.download) {
|
|
|
|
throw Error("expected proposal to be downloaded");
|
|
|
|
}
|
2022-10-09 02:23:06 +02:00
|
|
|
const download = p.download;
|
2022-10-21 15:11:41 +02:00
|
|
|
|
|
|
|
async function getFromTransaction(
|
|
|
|
tx: Exclude<typeof parentTx, undefined>,
|
|
|
|
): Promise<ReturnType<typeof expectProposalDownload>> {
|
|
|
|
const contractTerms = await tx.contractTerms.get(
|
|
|
|
download.contractTermsHash,
|
|
|
|
);
|
|
|
|
if (!contractTerms) {
|
|
|
|
throw Error("contract terms not found");
|
|
|
|
}
|
|
|
|
return {
|
|
|
|
contractData: extractContractData(
|
|
|
|
contractTerms.contractTermsRaw,
|
|
|
|
download.contractTermsHash,
|
|
|
|
download.contractTermsMerchantSig,
|
|
|
|
),
|
|
|
|
contractTermsRaw: contractTerms.contractTermsRaw,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
if (parentTx) {
|
|
|
|
return getFromTransaction(parentTx);
|
|
|
|
}
|
2022-10-09 02:23:06 +02:00
|
|
|
return await ws.db
|
|
|
|
.mktx((x) => [x.contractTerms])
|
2022-10-21 15:11:41 +02:00
|
|
|
.runReadOnly(getFromTransaction);
|
2022-10-08 20:56:57 +02:00
|
|
|
}
|
|
|
|
|
2021-01-18 23:35:41 +01:00
|
|
|
export function extractContractData(
|
2022-11-01 11:34:20 +01:00
|
|
|
parsedContractTerms: MerchantContractTerms,
|
2021-01-18 23:35:41 +01:00
|
|
|
contractTermsHash: string,
|
|
|
|
merchantSig: string,
|
|
|
|
): WalletContractData {
|
|
|
|
const amount = Amounts.parseOrThrow(parsedContractTerms.amount);
|
|
|
|
let maxWireFee: AmountJson;
|
|
|
|
if (parsedContractTerms.max_wire_fee) {
|
|
|
|
maxWireFee = Amounts.parseOrThrow(parsedContractTerms.max_wire_fee);
|
|
|
|
} else {
|
2022-11-02 17:42:14 +01:00
|
|
|
maxWireFee = Amounts.zeroOfCurrency(amount.currency);
|
2021-01-18 23:35:41 +01:00
|
|
|
}
|
|
|
|
return {
|
2022-11-02 17:42:14 +01:00
|
|
|
amount: Amounts.stringify(amount),
|
2021-01-18 23:35:41 +01:00
|
|
|
contractTermsHash: contractTermsHash,
|
|
|
|
fulfillmentUrl: parsedContractTerms.fulfillment_url ?? "",
|
|
|
|
merchantBaseUrl: parsedContractTerms.merchant_base_url,
|
|
|
|
merchantPub: parsedContractTerms.merchant_pub,
|
|
|
|
merchantSig,
|
|
|
|
orderId: parsedContractTerms.order_id,
|
|
|
|
summary: parsedContractTerms.summary,
|
|
|
|
autoRefund: parsedContractTerms.auto_refund,
|
2022-11-02 17:42:14 +01:00
|
|
|
maxWireFee: Amounts.stringify(maxWireFee),
|
2021-01-18 23:35:41 +01:00
|
|
|
payDeadline: parsedContractTerms.pay_deadline,
|
|
|
|
refundDeadline: parsedContractTerms.refund_deadline,
|
|
|
|
wireFeeAmortization: parsedContractTerms.wire_fee_amortization || 1,
|
|
|
|
allowedAuditors: parsedContractTerms.auditors.map((x) => ({
|
|
|
|
auditorBaseUrl: x.url,
|
|
|
|
auditorPub: x.auditor_pub,
|
|
|
|
})),
|
|
|
|
allowedExchanges: parsedContractTerms.exchanges.map((x) => ({
|
|
|
|
exchangeBaseUrl: x.url,
|
|
|
|
exchangePub: x.master_pub,
|
|
|
|
})),
|
|
|
|
timestamp: parsedContractTerms.timestamp,
|
|
|
|
wireMethod: parsedContractTerms.wire_method,
|
|
|
|
wireInfoHash: parsedContractTerms.h_wire,
|
2022-11-02 17:42:14 +01:00
|
|
|
maxDepositFee: Amounts.stringify(parsedContractTerms.max_fee),
|
2021-01-18 23:35:41 +01:00
|
|
|
merchant: parsedContractTerms.merchant,
|
|
|
|
products: parsedContractTerms.products,
|
|
|
|
summaryI18n: parsedContractTerms.summary_i18n,
|
2022-04-19 17:12:43 +02:00
|
|
|
minimumAge: parsedContractTerms.minimum_age,
|
2022-08-08 18:53:04 +02:00
|
|
|
deliveryDate: parsedContractTerms.delivery_date,
|
|
|
|
deliveryLocation: parsedContractTerms.delivery_location,
|
2021-01-18 23:35:41 +01:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2022-09-05 18:12:30 +02:00
|
|
|
export async function processDownloadProposal(
|
2019-12-05 19:38:19 +01:00
|
|
|
ws: InternalWalletState,
|
|
|
|
proposalId: string,
|
2022-09-16 16:06:55 +02:00
|
|
|
options: object = {},
|
2022-09-05 18:12:30 +02:00
|
|
|
): Promise<OperationAttemptResult> {
|
2021-06-09 15:14:17 +02:00
|
|
|
const proposal = await ws.db
|
2022-10-08 20:56:57 +02:00
|
|
|
.mktx((x) => [x.purchases])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadOnly(async (tx) => {
|
2022-10-08 20:56:57 +02:00
|
|
|
return await tx.purchases.get(proposalId);
|
2021-06-09 15:14:17 +02:00
|
|
|
});
|
2022-03-08 23:09:20 +01:00
|
|
|
|
2019-12-03 00:52:15 +01:00
|
|
|
if (!proposal) {
|
2022-09-05 18:12:30 +02:00
|
|
|
return {
|
|
|
|
type: OperationAttemptResultType.Finished,
|
|
|
|
result: undefined,
|
|
|
|
};
|
2019-12-03 00:52:15 +01:00
|
|
|
}
|
2022-03-08 23:09:20 +01:00
|
|
|
|
2022-10-08 23:45:49 +02:00
|
|
|
if (proposal.purchaseStatus != PurchaseStatus.DownloadingProposal) {
|
2022-09-05 18:12:30 +02:00
|
|
|
return {
|
|
|
|
type: OperationAttemptResultType.Finished,
|
|
|
|
result: undefined,
|
|
|
|
};
|
2019-12-03 00:52:15 +01:00
|
|
|
}
|
2019-12-07 22:02:11 +01:00
|
|
|
|
2020-07-20 14:16:49 +02:00
|
|
|
const orderClaimUrl = new URL(
|
|
|
|
`orders/${proposal.orderId}/claim`,
|
|
|
|
proposal.merchantBaseUrl,
|
|
|
|
).href;
|
|
|
|
logger.trace("downloading contract from '" + orderClaimUrl + "'");
|
|
|
|
|
2020-07-30 13:58:09 +02:00
|
|
|
const requestBody: {
|
2020-08-03 09:30:48 +02:00
|
|
|
nonce: string;
|
2020-07-30 13:58:09 +02:00
|
|
|
token?: string;
|
|
|
|
} = {
|
2020-07-22 10:52:03 +02:00
|
|
|
nonce: proposal.noncePub,
|
|
|
|
};
|
2020-07-30 13:58:09 +02:00
|
|
|
if (proposal.claimToken) {
|
|
|
|
requestBody.token = proposal.claimToken;
|
|
|
|
}
|
2020-07-22 10:52:03 +02:00
|
|
|
|
2022-10-08 20:56:57 +02:00
|
|
|
const opId = RetryTags.forPay(proposal);
|
2022-09-05 18:12:30 +02:00
|
|
|
const retryRecord = await ws.db
|
2022-09-13 13:25:41 +02:00
|
|
|
.mktx((x) => [x.operationRetries])
|
2022-09-05 18:12:30 +02:00
|
|
|
.runReadOnly(async (tx) => {
|
|
|
|
return tx.operationRetries.get(opId);
|
|
|
|
});
|
|
|
|
|
|
|
|
// FIXME: Do this in the background using the new return value
|
2020-08-24 08:22:12 +02:00
|
|
|
const httpResponse = await ws.http.postJson(orderClaimUrl, requestBody, {
|
2022-09-05 18:12:30 +02:00
|
|
|
timeout: getProposalRequestTimeout(retryRecord?.retryInfo),
|
2020-08-20 12:57:20 +02:00
|
|
|
});
|
2020-08-24 16:09:09 +02:00
|
|
|
const r = await readSuccessResponseJsonOrErrorCode(
|
|
|
|
httpResponse,
|
|
|
|
codecForProposal(),
|
|
|
|
);
|
2020-08-24 08:22:12 +02:00
|
|
|
if (r.isError) {
|
|
|
|
switch (r.talerErrorResponse.code) {
|
2020-11-08 01:20:50 +01:00
|
|
|
case TalerErrorCode.MERCHANT_POST_ORDERS_ID_CLAIM_ALREADY_CLAIMED:
|
2022-03-22 21:16:38 +01:00
|
|
|
throw TalerError.fromDetail(
|
2020-08-24 08:22:12 +02:00
|
|
|
TalerErrorCode.WALLET_ORDER_ALREADY_CLAIMED,
|
|
|
|
{
|
|
|
|
orderId: proposal.orderId,
|
|
|
|
claimUrl: orderClaimUrl,
|
2020-08-24 16:09:09 +02:00
|
|
|
},
|
2022-03-22 21:16:38 +01:00
|
|
|
"order already claimed (likely by other wallet)",
|
2020-08-24 16:09:09 +02:00
|
|
|
);
|
2020-08-24 08:22:12 +02:00
|
|
|
default:
|
|
|
|
throwUnexpectedRequestError(httpResponse, r.talerErrorResponse);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
const proposalResp = r.response;
|
2019-12-09 13:29:11 +01:00
|
|
|
|
2020-07-20 14:16:49 +02:00
|
|
|
// The proposalResp contains the contract terms as raw JSON,
|
|
|
|
// as the coded to parse them doesn't necessarily round-trip.
|
|
|
|
// We need this raw JSON to compute the contract terms hash.
|
2019-12-03 00:52:15 +01:00
|
|
|
|
2021-04-14 14:36:46 +02:00
|
|
|
// FIXME: Do better error handling, check if the
|
|
|
|
// contract terms have all their forgettable information still
|
|
|
|
// present. The wallet should never accept contract terms
|
|
|
|
// with missing information from the merchant.
|
|
|
|
|
|
|
|
const isWellFormed = ContractTermsUtil.validateForgettable(
|
|
|
|
proposalResp.contract_terms,
|
2019-12-03 00:52:15 +01:00
|
|
|
);
|
|
|
|
|
2021-04-14 14:36:46 +02:00
|
|
|
if (!isWellFormed) {
|
2021-06-22 13:52:28 +02:00
|
|
|
logger.trace(
|
|
|
|
`malformed contract terms: ${j2s(proposalResp.contract_terms)}`,
|
|
|
|
);
|
2022-03-22 21:16:38 +01:00
|
|
|
const err = makeErrorDetail(
|
2021-04-14 14:36:46 +02:00
|
|
|
TalerErrorCode.WALLET_CONTRACT_TERMS_MALFORMED,
|
|
|
|
{},
|
2022-03-22 21:16:38 +01:00
|
|
|
"validation for well-formedness failed",
|
2021-04-14 14:36:46 +02:00
|
|
|
);
|
|
|
|
await failProposalPermanently(ws, proposalId, err);
|
2022-03-22 21:16:38 +01:00
|
|
|
throw makePendingOperationFailedError(
|
|
|
|
err,
|
|
|
|
TransactionType.Payment,
|
|
|
|
proposalId,
|
|
|
|
);
|
2021-04-14 14:36:46 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
const contractTermsHash = ContractTermsUtil.hashContractTerms(
|
2019-12-19 20:42:49 +01:00
|
|
|
proposalResp.contract_terms,
|
|
|
|
);
|
2020-11-03 17:39:30 +01:00
|
|
|
|
2021-10-18 21:48:22 +02:00
|
|
|
logger.info(`Contract terms hash: ${contractTermsHash}`);
|
|
|
|
|
2022-11-01 11:34:20 +01:00
|
|
|
let parsedContractTerms: MerchantContractTerms;
|
2021-04-14 14:36:46 +02:00
|
|
|
|
|
|
|
try {
|
2022-11-08 17:00:34 +01:00
|
|
|
parsedContractTerms = codecForMerchantContractTerms().decode(
|
2021-04-14 14:36:46 +02:00
|
|
|
proposalResp.contract_terms,
|
|
|
|
);
|
|
|
|
} catch (e) {
|
2022-03-22 21:16:38 +01:00
|
|
|
const err = makeErrorDetail(
|
2021-04-14 14:36:46 +02:00
|
|
|
TalerErrorCode.WALLET_CONTRACT_TERMS_MALFORMED,
|
|
|
|
{},
|
2022-03-22 21:16:38 +01:00
|
|
|
`schema validation failed: ${e}`,
|
2021-04-14 14:36:46 +02:00
|
|
|
);
|
|
|
|
await failProposalPermanently(ws, proposalId, err);
|
2022-03-22 21:16:38 +01:00
|
|
|
throw makePendingOperationFailedError(
|
|
|
|
err,
|
|
|
|
TransactionType.Payment,
|
|
|
|
proposalId,
|
|
|
|
);
|
2021-04-14 14:36:46 +02:00
|
|
|
}
|
|
|
|
|
2022-03-23 21:24:23 +01:00
|
|
|
const sigValid = await ws.cryptoApi.isValidContractTermsSignature({
|
2020-11-03 17:39:30 +01:00
|
|
|
contractTermsHash,
|
2022-03-23 21:24:23 +01:00
|
|
|
merchantPub: parsedContractTerms.merchant_pub,
|
|
|
|
sig: proposalResp.sig,
|
|
|
|
});
|
2020-11-03 17:39:30 +01:00
|
|
|
|
|
|
|
if (!sigValid) {
|
2022-03-22 21:16:38 +01:00
|
|
|
const err = makeErrorDetail(
|
2020-11-03 17:39:30 +01:00
|
|
|
TalerErrorCode.WALLET_CONTRACT_TERMS_SIGNATURE_INVALID,
|
|
|
|
{
|
|
|
|
merchantPub: parsedContractTerms.merchant_pub,
|
|
|
|
orderId: parsedContractTerms.order_id,
|
|
|
|
},
|
2022-03-22 21:16:38 +01:00
|
|
|
"merchant's signature on contract terms is invalid",
|
2020-11-03 17:39:30 +01:00
|
|
|
);
|
|
|
|
await failProposalPermanently(ws, proposalId, err);
|
2022-03-22 21:16:38 +01:00
|
|
|
throw makePendingOperationFailedError(
|
|
|
|
err,
|
|
|
|
TransactionType.Payment,
|
|
|
|
proposalId,
|
|
|
|
);
|
2020-11-03 17:39:30 +01:00
|
|
|
}
|
|
|
|
|
2019-12-19 20:42:49 +01:00
|
|
|
const fulfillmentUrl = parsedContractTerms.fulfillment_url;
|
2019-12-03 00:52:15 +01:00
|
|
|
|
2020-11-03 16:46:43 +01:00
|
|
|
const baseUrlForDownload = proposal.merchantBaseUrl;
|
|
|
|
const baseUrlFromContractTerms = parsedContractTerms.merchant_base_url;
|
|
|
|
|
|
|
|
if (baseUrlForDownload !== baseUrlFromContractTerms) {
|
2022-03-22 21:16:38 +01:00
|
|
|
const err = makeErrorDetail(
|
2020-11-03 16:46:43 +01:00
|
|
|
TalerErrorCode.WALLET_CONTRACT_TERMS_BASE_URL_MISMATCH,
|
|
|
|
{
|
|
|
|
baseUrlForDownload,
|
|
|
|
baseUrlFromContractTerms,
|
|
|
|
},
|
2022-03-22 21:16:38 +01:00
|
|
|
"merchant base URL mismatch",
|
2020-11-03 16:46:43 +01:00
|
|
|
);
|
2020-11-03 17:39:30 +01:00
|
|
|
await failProposalPermanently(ws, proposalId, err);
|
2022-03-22 21:16:38 +01:00
|
|
|
throw makePendingOperationFailedError(
|
|
|
|
err,
|
|
|
|
TransactionType.Payment,
|
|
|
|
proposalId,
|
|
|
|
);
|
2020-11-03 16:46:43 +01:00
|
|
|
}
|
|
|
|
|
2021-01-18 23:35:41 +01:00
|
|
|
const contractData = extractContractData(
|
|
|
|
parsedContractTerms,
|
|
|
|
contractTermsHash,
|
|
|
|
proposalResp.sig,
|
|
|
|
);
|
|
|
|
|
2022-04-19 17:12:43 +02:00
|
|
|
logger.trace(`extracted contract data: ${j2s(contractData)}`);
|
|
|
|
|
2021-06-09 15:14:17 +02:00
|
|
|
await ws.db
|
2022-10-09 02:23:06 +02:00
|
|
|
.mktx((x) => [x.purchases, x.contractTerms])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadWrite(async (tx) => {
|
2022-10-08 20:56:57 +02:00
|
|
|
const p = await tx.purchases.get(proposalId);
|
2019-12-03 00:52:15 +01:00
|
|
|
if (!p) {
|
|
|
|
return;
|
|
|
|
}
|
2022-10-08 23:45:49 +02:00
|
|
|
if (p.purchaseStatus !== PurchaseStatus.DownloadingProposal) {
|
2019-12-03 00:52:15 +01:00
|
|
|
return;
|
|
|
|
}
|
2019-12-16 22:42:10 +01:00
|
|
|
p.download = {
|
2022-10-09 02:23:06 +02:00
|
|
|
contractTermsHash,
|
|
|
|
contractTermsMerchantSig: contractData.merchantSig,
|
2022-11-02 17:42:14 +01:00
|
|
|
currency: Amounts.currencyOf(contractData.amount),
|
2022-10-09 02:23:06 +02:00
|
|
|
fulfillmentUrl: contractData.fulfillmentUrl,
|
2019-12-16 22:42:10 +01:00
|
|
|
};
|
2022-10-09 02:23:06 +02:00
|
|
|
await tx.contractTerms.put({
|
|
|
|
h: contractTermsHash,
|
|
|
|
contractTermsRaw: proposalResp.contract_terms,
|
|
|
|
});
|
2019-12-03 00:52:15 +01:00
|
|
|
if (
|
2020-08-24 16:09:09 +02:00
|
|
|
fulfillmentUrl &&
|
|
|
|
(fulfillmentUrl.startsWith("http://") ||
|
|
|
|
fulfillmentUrl.startsWith("https://"))
|
2019-12-03 00:52:15 +01:00
|
|
|
) {
|
2022-01-13 22:01:14 +01:00
|
|
|
const differentPurchase =
|
|
|
|
await tx.purchases.indexes.byFulfillmentUrl.get(fulfillmentUrl);
|
2019-12-03 00:52:15 +01:00
|
|
|
if (differentPurchase) {
|
2020-08-14 12:23:50 +02:00
|
|
|
logger.warn("repurchase detected");
|
2022-10-08 23:45:49 +02:00
|
|
|
p.purchaseStatus = PurchaseStatus.RepurchaseDetected;
|
2019-12-03 00:52:15 +01:00
|
|
|
p.repurchaseProposalId = differentPurchase.proposalId;
|
2022-10-08 20:56:57 +02:00
|
|
|
await tx.purchases.put(p);
|
2019-12-03 00:52:15 +01:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
2022-10-08 23:45:49 +02:00
|
|
|
p.purchaseStatus = PurchaseStatus.Proposed;
|
2022-10-08 20:56:57 +02:00
|
|
|
await tx.purchases.put(p);
|
2021-06-09 15:14:17 +02:00
|
|
|
});
|
2019-12-03 00:52:15 +01:00
|
|
|
|
2019-12-05 19:38:19 +01:00
|
|
|
ws.notify({
|
|
|
|
type: NotificationType.ProposalDownloaded,
|
|
|
|
proposalId: proposal.proposalId,
|
|
|
|
});
|
2022-09-05 18:12:30 +02:00
|
|
|
|
|
|
|
return {
|
|
|
|
type: OperationAttemptResultType.Finished,
|
|
|
|
result: undefined,
|
|
|
|
};
|
2019-12-03 00:52:15 +01:00
|
|
|
}
|
|
|
|
|
2019-12-02 00:42:40 +01:00
|
|
|
/**
|
|
|
|
* Download a proposal and store it in the database.
|
|
|
|
* Returns an id for it to retrieve it later.
|
|
|
|
*
|
|
|
|
* @param sessionId Current session ID, if the proposal is being
|
|
|
|
* downloaded in the context of a session ID.
|
|
|
|
*/
|
2019-12-03 00:52:15 +01:00
|
|
|
async function startDownloadProposal(
|
2019-12-02 00:42:40 +01:00
|
|
|
ws: InternalWalletState,
|
2019-12-06 12:47:28 +01:00
|
|
|
merchantBaseUrl: string,
|
|
|
|
orderId: string,
|
2019-12-10 12:22:29 +01:00
|
|
|
sessionId: string | undefined,
|
2020-07-30 13:58:09 +02:00
|
|
|
claimToken: string | undefined,
|
2021-09-17 20:48:33 +02:00
|
|
|
noncePriv: string | undefined,
|
2019-12-02 00:42:40 +01:00
|
|
|
): Promise<string> {
|
2021-06-09 15:14:17 +02:00
|
|
|
const oldProposal = await ws.db
|
2022-10-08 20:56:57 +02:00
|
|
|
.mktx((x) => [x.purchases])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadOnly(async (tx) => {
|
2022-10-08 20:56:57 +02:00
|
|
|
return tx.purchases.indexes.byUrlAndOrderId.get([
|
2021-06-09 15:14:17 +02:00
|
|
|
merchantBaseUrl,
|
|
|
|
orderId,
|
|
|
|
]);
|
|
|
|
});
|
2021-11-27 20:56:58 +01:00
|
|
|
|
2022-03-22 21:16:38 +01:00
|
|
|
/* If we have already claimed this proposal with the same sessionId
|
|
|
|
* nonce and claim token, reuse it. */
|
2021-11-27 20:56:58 +01:00
|
|
|
if (
|
|
|
|
oldProposal &&
|
|
|
|
oldProposal.downloadSessionId === sessionId &&
|
|
|
|
(!noncePriv || oldProposal.noncePriv === noncePriv) &&
|
|
|
|
oldProposal.claimToken === claimToken
|
|
|
|
) {
|
2019-12-03 00:52:15 +01:00
|
|
|
await processDownloadProposal(ws, oldProposal.proposalId);
|
2019-12-02 00:42:40 +01:00
|
|
|
return oldProposal.proposalId;
|
|
|
|
}
|
|
|
|
|
2022-03-23 21:24:23 +01:00
|
|
|
let noncePair: EddsaKeypair;
|
|
|
|
if (noncePriv) {
|
2022-03-24 01:59:08 +01:00
|
|
|
noncePair = {
|
|
|
|
priv: noncePriv,
|
|
|
|
pub: (await ws.cryptoApi.eddsaGetPublic({ priv: noncePriv })).pub,
|
|
|
|
};
|
2022-03-23 21:24:23 +01:00
|
|
|
} else {
|
|
|
|
noncePair = await ws.cryptoApi.createEddsaKeypair({});
|
|
|
|
}
|
|
|
|
|
|
|
|
const { priv, pub } = noncePair;
|
2019-12-02 00:42:40 +01:00
|
|
|
const proposalId = encodeCrock(getRandomBytes(32));
|
|
|
|
|
2022-10-08 20:56:57 +02:00
|
|
|
const proposalRecord: PurchaseRecord = {
|
2019-12-03 00:52:15 +01:00
|
|
|
download: undefined,
|
2019-12-02 00:42:40 +01:00
|
|
|
noncePriv: priv,
|
2019-12-03 00:52:15 +01:00
|
|
|
noncePub: pub,
|
2020-07-30 13:58:09 +02:00
|
|
|
claimToken,
|
2022-03-18 15:32:41 +01:00
|
|
|
timestamp: AbsoluteTime.toTimestamp(AbsoluteTime.now()),
|
2019-12-06 12:47:28 +01:00
|
|
|
merchantBaseUrl,
|
|
|
|
orderId,
|
2019-12-02 00:42:40 +01:00
|
|
|
proposalId: proposalId,
|
2022-10-08 23:45:49 +02:00
|
|
|
purchaseStatus: PurchaseStatus.DownloadingProposal,
|
2019-12-03 00:52:15 +01:00
|
|
|
repurchaseProposalId: undefined,
|
2019-12-10 12:22:29 +01:00
|
|
|
downloadSessionId: sessionId,
|
2022-10-08 20:56:57 +02:00
|
|
|
autoRefundDeadline: undefined,
|
|
|
|
lastSessionId: undefined,
|
|
|
|
merchantPaySig: undefined,
|
|
|
|
payInfo: undefined,
|
|
|
|
refundAmountAwaiting: undefined,
|
|
|
|
refunds: {},
|
|
|
|
timestampAccept: undefined,
|
|
|
|
timestampFirstSuccessfulPay: undefined,
|
|
|
|
timestampLastRefundStatus: undefined,
|
|
|
|
pendingRemovedCoinPubs: undefined,
|
2019-12-02 00:42:40 +01:00
|
|
|
};
|
|
|
|
|
2021-06-09 15:14:17 +02:00
|
|
|
await ws.db
|
2022-10-08 20:56:57 +02:00
|
|
|
.mktx((x) => [x.purchases])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadWrite(async (tx) => {
|
2022-10-08 20:56:57 +02:00
|
|
|
const existingRecord = await tx.purchases.indexes.byUrlAndOrderId.get([
|
2021-06-09 15:14:17 +02:00
|
|
|
merchantBaseUrl,
|
|
|
|
orderId,
|
|
|
|
]);
|
|
|
|
if (existingRecord) {
|
|
|
|
// Created concurrently
|
|
|
|
return;
|
|
|
|
}
|
2022-10-08 20:56:57 +02:00
|
|
|
await tx.purchases.put(proposalRecord);
|
2021-06-09 15:14:17 +02:00
|
|
|
});
|
2019-12-10 12:22:29 +01:00
|
|
|
|
2019-12-03 00:52:15 +01:00
|
|
|
await processDownloadProposal(ws, proposalId);
|
2019-12-02 00:42:40 +01:00
|
|
|
return proposalId;
|
|
|
|
}
|
|
|
|
|
2020-08-19 17:25:38 +02:00
|
|
|
async function storeFirstPaySuccess(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
proposalId: string,
|
|
|
|
sessionId: string | undefined,
|
|
|
|
paySig: string,
|
|
|
|
): Promise<void> {
|
2022-03-18 15:32:41 +01:00
|
|
|
const now = AbsoluteTime.toTimestamp(AbsoluteTime.now());
|
2021-06-09 15:14:17 +02:00
|
|
|
await ws.db
|
2022-10-09 02:23:06 +02:00
|
|
|
.mktx((x) => [x.purchases, x.contractTerms])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadWrite(async (tx) => {
|
|
|
|
const purchase = await tx.purchases.get(proposalId);
|
2020-08-19 17:25:38 +02:00
|
|
|
|
2021-06-09 15:14:17 +02:00
|
|
|
if (!purchase) {
|
|
|
|
logger.warn("purchase does not exist anymore");
|
|
|
|
return;
|
2020-08-19 17:25:38 +02:00
|
|
|
}
|
2021-06-09 15:14:17 +02:00
|
|
|
const isFirst = purchase.timestampFirstSuccessfulPay === undefined;
|
|
|
|
if (!isFirst) {
|
|
|
|
logger.warn("payment success already stored");
|
|
|
|
return;
|
|
|
|
}
|
2022-10-08 23:45:49 +02:00
|
|
|
if (purchase.purchaseStatus === PurchaseStatus.Paying) {
|
|
|
|
purchase.purchaseStatus = PurchaseStatus.Paid;
|
2022-10-08 20:56:57 +02:00
|
|
|
}
|
2021-06-09 15:14:17 +02:00
|
|
|
purchase.timestampFirstSuccessfulPay = now;
|
|
|
|
purchase.lastSessionId = sessionId;
|
|
|
|
purchase.merchantPaySig = paySig;
|
2022-10-09 02:23:06 +02:00
|
|
|
const dl = purchase.download;
|
|
|
|
checkDbInvariant(!!dl);
|
|
|
|
const contractTermsRecord = await tx.contractTerms.get(
|
|
|
|
dl.contractTermsHash,
|
|
|
|
);
|
|
|
|
checkDbInvariant(!!contractTermsRecord);
|
|
|
|
const contractData = extractContractData(
|
|
|
|
contractTermsRecord.contractTermsRaw,
|
|
|
|
dl.contractTermsHash,
|
|
|
|
dl.contractTermsMerchantSig,
|
|
|
|
);
|
|
|
|
const protoAr = contractData.autoRefund;
|
2022-05-14 23:09:33 +02:00
|
|
|
if (protoAr) {
|
|
|
|
const ar = Duration.fromTalerProtocolDuration(protoAr);
|
|
|
|
logger.info("auto_refund present");
|
2022-10-08 23:45:49 +02:00
|
|
|
purchase.purchaseStatus = PurchaseStatus.QueryingAutoRefund;
|
2022-05-14 23:09:33 +02:00
|
|
|
purchase.autoRefundDeadline = AbsoluteTime.toTimestamp(
|
|
|
|
AbsoluteTime.addDuration(AbsoluteTime.now(), ar),
|
|
|
|
);
|
2021-06-09 15:14:17 +02:00
|
|
|
}
|
|
|
|
await tx.purchases.put(purchase);
|
|
|
|
});
|
2020-08-19 17:25:38 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
async function storePayReplaySuccess(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
proposalId: string,
|
|
|
|
sessionId: string | undefined,
|
|
|
|
): Promise<void> {
|
2021-06-09 15:14:17 +02:00
|
|
|
await ws.db
|
2022-09-13 13:25:41 +02:00
|
|
|
.mktx((x) => [x.purchases])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadWrite(async (tx) => {
|
|
|
|
const purchase = await tx.purchases.get(proposalId);
|
2020-08-19 17:25:38 +02:00
|
|
|
|
2021-06-09 15:14:17 +02:00
|
|
|
if (!purchase) {
|
|
|
|
logger.warn("purchase does not exist anymore");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const isFirst = purchase.timestampFirstSuccessfulPay === undefined;
|
|
|
|
if (isFirst) {
|
|
|
|
throw Error("invalid payment state");
|
|
|
|
}
|
2022-10-21 16:06:31 +02:00
|
|
|
if (
|
|
|
|
purchase.purchaseStatus === PurchaseStatus.Paying ||
|
|
|
|
purchase.purchaseStatus === PurchaseStatus.PayingReplay
|
|
|
|
) {
|
2022-10-08 23:45:49 +02:00
|
|
|
purchase.purchaseStatus = PurchaseStatus.Paid;
|
2022-10-08 20:56:57 +02:00
|
|
|
}
|
2021-06-09 15:14:17 +02:00
|
|
|
purchase.lastSessionId = sessionId;
|
|
|
|
await tx.purchases.put(purchase);
|
|
|
|
});
|
2020-08-19 17:25:38 +02:00
|
|
|
}
|
|
|
|
|
2021-03-11 13:08:41 +01:00
|
|
|
/**
|
|
|
|
* Handle a 409 Conflict response from the merchant.
|
|
|
|
*
|
|
|
|
* We do this by going through the coin history provided by the exchange and
|
|
|
|
* (1) verifying the signatures from the exchange
|
2021-04-07 19:29:51 +02:00
|
|
|
* (2) adjusting the remaining coin value and refreshing it
|
2021-03-15 13:43:53 +01:00
|
|
|
* (3) re-do coin selection with the bad coin removed
|
2021-03-11 13:08:41 +01:00
|
|
|
*/
|
|
|
|
async function handleInsufficientFunds(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
proposalId: string,
|
2022-03-22 21:16:38 +01:00
|
|
|
err: TalerErrorDetail,
|
2021-03-11 13:08:41 +01:00
|
|
|
): Promise<void> {
|
2021-04-07 19:29:51 +02:00
|
|
|
logger.trace("handling insufficient funds, trying to re-select coins");
|
|
|
|
|
2021-06-09 15:14:17 +02:00
|
|
|
const proposal = await ws.db
|
2022-09-13 13:25:41 +02:00
|
|
|
.mktx((x) => [x.purchases])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadOnly(async (tx) => {
|
2022-09-13 13:25:41 +02:00
|
|
|
return tx.purchases.get(proposalId);
|
2021-06-09 15:14:17 +02:00
|
|
|
});
|
2021-03-15 13:43:53 +01:00
|
|
|
if (!proposal) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-09-21 12:40:02 +02:00
|
|
|
logger.trace(`got error details: ${j2s(err)}`);
|
2021-04-07 19:29:51 +02:00
|
|
|
|
|
|
|
const exchangeReply = (err as any).exchange_reply;
|
|
|
|
if (
|
2022-03-08 23:09:20 +01:00
|
|
|
exchangeReply.code !== TalerErrorCode.EXCHANGE_GENERIC_INSUFFICIENT_FUNDS
|
2021-04-07 19:29:51 +02:00
|
|
|
) {
|
|
|
|
// FIXME: set as failed
|
2022-03-08 23:09:20 +01:00
|
|
|
if (logger.shouldLogTrace()) {
|
|
|
|
logger.trace("got exchange error reply (see below)");
|
|
|
|
logger.trace(j2s(exchangeReply));
|
|
|
|
}
|
|
|
|
throw Error(`unable to handle /pay error response (${exchangeReply.code})`);
|
2021-04-07 19:29:51 +02:00
|
|
|
}
|
|
|
|
|
2022-09-21 12:40:02 +02:00
|
|
|
const brokenCoinPub = (exchangeReply as any).coin_pub;
|
|
|
|
logger.trace(`excluded broken coin pub=${brokenCoinPub}`);
|
|
|
|
|
|
|
|
if (!brokenCoinPub) {
|
|
|
|
throw new TalerProtocolViolationError();
|
|
|
|
}
|
2021-04-07 19:29:51 +02:00
|
|
|
|
2022-10-09 02:23:06 +02:00
|
|
|
const { contractData } = await expectProposalDownload(ws, proposal);
|
2021-04-07 19:29:51 +02:00
|
|
|
|
|
|
|
const prevPayCoins: PreviousPayCoins = [];
|
|
|
|
|
2022-10-08 20:56:57 +02:00
|
|
|
const payInfo = proposal.payInfo;
|
|
|
|
if (!payInfo) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const payCoinSelection = payInfo.payCoinSelection;
|
|
|
|
|
2021-06-09 15:14:17 +02:00
|
|
|
await ws.db
|
2022-09-13 13:25:41 +02:00
|
|
|
.mktx((x) => [x.coins, x.denominations])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadOnly(async (tx) => {
|
2022-10-08 20:56:57 +02:00
|
|
|
for (let i = 0; i < payCoinSelection.coinPubs.length; i++) {
|
|
|
|
const coinPub = payCoinSelection.coinPubs[i];
|
2021-06-09 15:14:17 +02:00
|
|
|
if (coinPub === brokenCoinPub) {
|
|
|
|
continue;
|
|
|
|
}
|
2022-10-08 20:56:57 +02:00
|
|
|
const contrib = payCoinSelection.coinContributions[i];
|
2021-06-09 15:14:17 +02:00
|
|
|
const coin = await tx.coins.get(coinPub);
|
|
|
|
if (!coin) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
const denom = await tx.denominations.get([
|
|
|
|
coin.exchangeBaseUrl,
|
|
|
|
coin.denomPubHash,
|
|
|
|
]);
|
|
|
|
if (!denom) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
prevPayCoins.push({
|
|
|
|
coinPub,
|
2022-11-02 17:42:14 +01:00
|
|
|
contribution: Amounts.parseOrThrow(contrib),
|
2021-06-09 15:14:17 +02:00
|
|
|
exchangeBaseUrl: coin.exchangeBaseUrl,
|
2022-11-02 17:42:14 +01:00
|
|
|
feeDeposit: Amounts.parseOrThrow(denom.fees.feeDeposit),
|
2021-06-09 15:14:17 +02:00
|
|
|
});
|
|
|
|
}
|
2021-04-07 19:29:51 +02:00
|
|
|
});
|
|
|
|
|
2022-09-15 21:00:36 +02:00
|
|
|
const res = await selectPayCoinsNew(ws, {
|
|
|
|
auditors: contractData.allowedAuditors,
|
|
|
|
exchanges: contractData.allowedExchanges,
|
|
|
|
wireMethod: contractData.wireMethod,
|
2022-11-02 17:42:14 +01:00
|
|
|
contractTermsAmount: Amounts.parseOrThrow(contractData.amount),
|
|
|
|
depositFeeLimit: Amounts.parseOrThrow(contractData.maxDepositFee),
|
2021-04-07 19:29:51 +02:00
|
|
|
wireFeeAmortization: contractData.wireFeeAmortization ?? 1,
|
2022-11-02 17:42:14 +01:00
|
|
|
wireFeeLimit: Amounts.parseOrThrow(contractData.maxWireFee),
|
2021-04-07 19:29:51 +02:00
|
|
|
prevPayCoins,
|
2022-04-29 21:05:17 +02:00
|
|
|
requiredMinimumAge: contractData.minimumAge,
|
2021-04-07 19:29:51 +02:00
|
|
|
});
|
|
|
|
|
2023-01-05 18:45:49 +01:00
|
|
|
if (res.type !== "success") {
|
2021-04-07 19:29:51 +02:00
|
|
|
logger.trace("insufficient funds for coin re-selection");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.trace("re-selected coins");
|
|
|
|
|
2021-06-09 15:14:17 +02:00
|
|
|
await ws.db
|
2022-09-16 16:20:47 +02:00
|
|
|
.mktx((x) => [
|
|
|
|
x.purchases,
|
|
|
|
x.coins,
|
|
|
|
x.coinAvailability,
|
|
|
|
x.denominations,
|
|
|
|
x.refreshGroups,
|
|
|
|
])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadWrite(async (tx) => {
|
|
|
|
const p = await tx.purchases.get(proposalId);
|
2021-04-07 19:29:51 +02:00
|
|
|
if (!p) {
|
|
|
|
return;
|
|
|
|
}
|
2022-10-08 20:56:57 +02:00
|
|
|
const payInfo = p.payInfo;
|
|
|
|
if (!payInfo) {
|
|
|
|
return;
|
|
|
|
}
|
2023-01-05 18:45:49 +01:00
|
|
|
payInfo.payCoinSelection = res.coinSel;
|
2022-10-08 20:56:57 +02:00
|
|
|
payInfo.payCoinSelectionUid = encodeCrock(getRandomBytes(32));
|
2021-06-09 15:14:17 +02:00
|
|
|
await tx.purchases.put(p);
|
2022-09-14 20:34:37 +02:00
|
|
|
await spendCoins(ws, tx, {
|
2022-10-14 22:47:11 +02:00
|
|
|
allocationId: `txn:proposal:${p.proposalId}`,
|
2022-10-08 20:56:57 +02:00
|
|
|
coinPubs: payInfo.payCoinSelection.coinPubs,
|
2022-11-02 17:42:14 +01:00
|
|
|
contributions: payInfo.payCoinSelection.coinContributions.map((x) =>
|
|
|
|
Amounts.parseOrThrow(x),
|
|
|
|
),
|
2022-09-14 20:34:37 +02:00
|
|
|
refreshReason: RefreshReason.PayMerchant,
|
|
|
|
});
|
2021-06-09 15:14:17 +02:00
|
|
|
});
|
2021-03-11 13:08:41 +01:00
|
|
|
}
|
|
|
|
|
2021-06-25 13:27:06 +02:00
|
|
|
async function unblockBackup(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
proposalId: string,
|
|
|
|
): Promise<void> {
|
|
|
|
await ws.db
|
2022-09-13 13:25:41 +02:00
|
|
|
.mktx((x) => [x.backupProviders])
|
2021-06-25 13:27:06 +02:00
|
|
|
.runReadWrite(async (tx) => {
|
2022-01-16 21:47:43 +01:00
|
|
|
await tx.backupProviders.indexes.byPaymentProposalId
|
2021-06-25 13:27:06 +02:00
|
|
|
.iter(proposalId)
|
|
|
|
.forEachAsync(async (bp) => {
|
2022-10-21 16:08:10 +02:00
|
|
|
bp.state = {
|
|
|
|
tag: BackupProviderStateTag.Ready,
|
2022-10-21 17:14:06 +02:00
|
|
|
nextBackupTimestamp: TalerProtocolTimestamp.now(),
|
2022-10-21 16:08:10 +02:00
|
|
|
};
|
|
|
|
tx.backupProviders.put(bp);
|
2021-06-25 13:27:06 +02:00
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-09-15 20:16:42 +02:00
|
|
|
export interface SelectPayCoinRequestNg {
|
2022-09-15 21:00:36 +02:00
|
|
|
exchanges: AllowedExchangeInfo[];
|
|
|
|
auditors: AllowedAuditorInfo[];
|
2022-09-15 20:16:42 +02:00
|
|
|
wireMethod: string;
|
|
|
|
contractTermsAmount: AmountJson;
|
|
|
|
depositFeeLimit: AmountJson;
|
|
|
|
wireFeeLimit: AmountJson;
|
|
|
|
wireFeeAmortization: number;
|
|
|
|
prevPayCoins?: PreviousPayCoins;
|
|
|
|
requiredMinimumAge?: number;
|
2022-09-15 21:00:36 +02:00
|
|
|
forcedSelection?: ForcedCoinSel;
|
2022-09-15 20:16:42 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export type AvailableDenom = DenominationInfo & {
|
2022-09-16 16:20:47 +02:00
|
|
|
maxAge: number;
|
2022-09-15 20:16:42 +02:00
|
|
|
numAvailable: number;
|
|
|
|
};
|
|
|
|
|
2022-09-16 16:24:47 +02:00
|
|
|
export async function selectCandidates(
|
2022-09-15 20:16:42 +02:00
|
|
|
ws: InternalWalletState,
|
|
|
|
req: SelectPayCoinRequestNg,
|
2022-09-15 21:00:36 +02:00
|
|
|
): Promise<[AvailableDenom[], Record<string, AmountJson>]> {
|
|
|
|
return await ws.db
|
2022-09-16 16:20:47 +02:00
|
|
|
.mktx((x) => [
|
|
|
|
x.exchanges,
|
|
|
|
x.exchangeDetails,
|
|
|
|
x.denominations,
|
|
|
|
x.coinAvailability,
|
|
|
|
])
|
2022-09-15 20:16:42 +02:00
|
|
|
.runReadOnly(async (tx) => {
|
2023-01-05 18:45:49 +01:00
|
|
|
// FIXME: Use the existing helper (from balance.ts) to
|
|
|
|
// get acceptable exchanges.
|
2022-09-15 20:16:42 +02:00
|
|
|
const denoms: AvailableDenom[] = [];
|
|
|
|
const exchanges = await tx.exchanges.iter().toArray();
|
|
|
|
const wfPerExchange: Record<string, AmountJson> = {};
|
|
|
|
for (const exchange of exchanges) {
|
|
|
|
const exchangeDetails = await getExchangeDetails(tx, exchange.baseUrl);
|
2022-09-15 21:00:36 +02:00
|
|
|
if (exchangeDetails?.currency !== req.contractTermsAmount.currency) {
|
2022-09-15 20:16:42 +02:00
|
|
|
continue;
|
|
|
|
}
|
2022-09-19 11:28:47 +02:00
|
|
|
let wireMethodSupported = false;
|
|
|
|
for (const acc of exchangeDetails.wireInfo.accounts) {
|
|
|
|
const pp = parsePaytoUri(acc.payto_uri);
|
|
|
|
checkLogicInvariant(!!pp);
|
|
|
|
if (pp.targetType === req.wireMethod) {
|
|
|
|
wireMethodSupported = true;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!wireMethodSupported) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
exchangeDetails.wireInfo.accounts;
|
2022-09-15 20:16:42 +02:00
|
|
|
let accepted = false;
|
2022-09-15 21:00:36 +02:00
|
|
|
for (const allowedExchange of req.exchanges) {
|
|
|
|
if (allowedExchange.exchangePub === exchangeDetails.masterPublicKey) {
|
|
|
|
accepted = true;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for (const allowedAuditor of req.auditors) {
|
|
|
|
for (const providedAuditor of exchangeDetails.auditors) {
|
|
|
|
if (allowedAuditor.auditorPub === providedAuditor.auditor_pub) {
|
2022-09-15 20:16:42 +02:00
|
|
|
accepted = true;
|
2022-09-15 21:00:36 +02:00
|
|
|
break;
|
2022-09-15 20:16:42 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!accepted) {
|
|
|
|
continue;
|
|
|
|
}
|
2022-09-16 16:20:47 +02:00
|
|
|
let ageLower = 0;
|
2022-09-16 16:24:47 +02:00
|
|
|
let ageUpper = AgeRestriction.AGE_UNRESTRICTED;
|
2022-09-16 16:20:47 +02:00
|
|
|
if (req.requiredMinimumAge) {
|
|
|
|
ageLower = req.requiredMinimumAge;
|
|
|
|
}
|
|
|
|
const myExchangeDenoms =
|
|
|
|
await tx.coinAvailability.indexes.byExchangeAgeAvailability.getAll(
|
|
|
|
GlobalIDB.KeyRange.bound(
|
|
|
|
[exchangeDetails.exchangeBaseUrl, ageLower, 1],
|
|
|
|
[
|
|
|
|
exchangeDetails.exchangeBaseUrl,
|
|
|
|
ageUpper,
|
|
|
|
Number.MAX_SAFE_INTEGER,
|
|
|
|
],
|
|
|
|
),
|
|
|
|
);
|
2022-09-15 21:00:36 +02:00
|
|
|
// FIXME: Check that the individual denomination is audited!
|
2022-09-15 20:16:42 +02:00
|
|
|
// FIXME: Should we exclude denominations that are
|
|
|
|
// not spendable anymore?
|
2022-09-16 16:20:47 +02:00
|
|
|
for (const denomAvail of myExchangeDenoms) {
|
|
|
|
const denom = await tx.denominations.get([
|
|
|
|
denomAvail.exchangeBaseUrl,
|
|
|
|
denomAvail.denomPubHash,
|
|
|
|
]);
|
|
|
|
checkDbInvariant(!!denom);
|
2022-09-19 12:21:00 +02:00
|
|
|
if (denom.isRevoked || !denom.isOffered) {
|
2022-09-19 12:19:58 +02:00
|
|
|
continue;
|
|
|
|
}
|
2022-09-15 20:16:42 +02:00
|
|
|
denoms.push({
|
|
|
|
...DenominationRecord.toDenomInfo(denom),
|
2022-09-16 16:20:47 +02:00
|
|
|
numAvailable: denomAvail.freshCoinCount ?? 0,
|
|
|
|
maxAge: denomAvail.maxAge,
|
2022-09-15 20:16:42 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2022-09-15 21:00:36 +02:00
|
|
|
// Sort by available amount (descending), deposit fee (ascending) and
|
|
|
|
// denomPub (ascending) if deposit fee is the same
|
|
|
|
// (to guarantee deterministic results)
|
|
|
|
denoms.sort(
|
|
|
|
(o1, o2) =>
|
|
|
|
-Amounts.cmp(o1.value, o2.value) ||
|
|
|
|
Amounts.cmp(o1.feeDeposit, o2.feeDeposit) ||
|
|
|
|
strcmp(o1.denomPubHash, o2.denomPubHash),
|
|
|
|
);
|
2022-09-15 20:16:42 +02:00
|
|
|
return [denoms, wfPerExchange];
|
|
|
|
});
|
2022-09-15 21:00:36 +02:00
|
|
|
}
|
2022-09-15 20:16:42 +02:00
|
|
|
|
2022-09-16 16:20:47 +02:00
|
|
|
function makeAvailabilityKey(
|
|
|
|
exchangeBaseUrl: string,
|
|
|
|
denomPubHash: string,
|
|
|
|
maxAge: number,
|
|
|
|
): string {
|
|
|
|
return `${denomPubHash};${maxAge};${exchangeBaseUrl}`;
|
|
|
|
}
|
|
|
|
|
2022-09-15 21:00:36 +02:00
|
|
|
/**
|
|
|
|
* Selection result.
|
|
|
|
*/
|
|
|
|
interface SelResult {
|
|
|
|
/**
|
2022-09-16 16:20:47 +02:00
|
|
|
* Map from an availability key
|
2022-09-15 21:00:36 +02:00
|
|
|
* to an array of contributions.
|
|
|
|
*/
|
2022-09-16 16:20:47 +02:00
|
|
|
[avKey: string]: {
|
|
|
|
exchangeBaseUrl: string;
|
|
|
|
denomPubHash: string;
|
|
|
|
maxAge: number;
|
|
|
|
contributions: AmountJson[];
|
|
|
|
};
|
2022-09-15 21:00:36 +02:00
|
|
|
}
|
2022-09-15 20:16:42 +02:00
|
|
|
|
2022-09-15 21:00:36 +02:00
|
|
|
export function selectGreedy(
|
|
|
|
req: SelectPayCoinRequestNg,
|
|
|
|
candidateDenoms: AvailableDenom[],
|
|
|
|
wireFeesPerExchange: Record<string, AmountJson>,
|
|
|
|
tally: CoinSelectionTally,
|
|
|
|
): SelResult | undefined {
|
|
|
|
const { wireFeeAmortization } = req;
|
|
|
|
const selectedDenom: SelResult = {};
|
2022-09-15 20:16:42 +02:00
|
|
|
for (const aci of candidateDenoms) {
|
|
|
|
const contributions: AmountJson[] = [];
|
|
|
|
for (let i = 0; i < aci.numAvailable; i++) {
|
|
|
|
// Don't use this coin if depositing it is more expensive than
|
|
|
|
// the amount it would give the merchant.
|
|
|
|
if (Amounts.cmp(aci.feeDeposit, aci.value) > 0) {
|
2023-01-05 18:45:49 +01:00
|
|
|
tally.lastDepositFee = Amounts.parseOrThrow(aci.feeDeposit);
|
2022-09-15 20:16:42 +02:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Amounts.isZero(tally.amountPayRemaining)) {
|
|
|
|
// We have spent enough!
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
tally = tallyFees(
|
|
|
|
tally,
|
|
|
|
wireFeesPerExchange,
|
|
|
|
wireFeeAmortization,
|
|
|
|
aci.exchangeBaseUrl,
|
2022-11-02 17:42:14 +01:00
|
|
|
Amounts.parseOrThrow(aci.feeDeposit),
|
2022-09-15 20:16:42 +02:00
|
|
|
);
|
|
|
|
|
|
|
|
let coinSpend = Amounts.max(
|
|
|
|
Amounts.min(tally.amountPayRemaining, aci.value),
|
|
|
|
aci.feeDeposit,
|
|
|
|
);
|
|
|
|
|
|
|
|
tally.amountPayRemaining = Amounts.sub(
|
|
|
|
tally.amountPayRemaining,
|
|
|
|
coinSpend,
|
|
|
|
).amount;
|
|
|
|
contributions.push(coinSpend);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (contributions.length) {
|
2022-09-16 16:20:47 +02:00
|
|
|
const avKey = makeAvailabilityKey(
|
|
|
|
aci.exchangeBaseUrl,
|
|
|
|
aci.denomPubHash,
|
|
|
|
aci.maxAge,
|
|
|
|
);
|
|
|
|
let sd = selectedDenom[avKey];
|
|
|
|
if (!sd) {
|
|
|
|
sd = {
|
|
|
|
contributions: [],
|
|
|
|
denomPubHash: aci.denomPubHash,
|
|
|
|
exchangeBaseUrl: aci.exchangeBaseUrl,
|
|
|
|
maxAge: aci.maxAge,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
sd.contributions.push(...contributions);
|
|
|
|
selectedDenom[avKey] = sd;
|
2022-09-15 20:16:42 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if (Amounts.isZero(tally.amountPayRemaining)) {
|
2022-09-15 21:00:36 +02:00
|
|
|
return selectedDenom;
|
2022-09-15 20:16:42 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
|
2022-09-15 21:00:36 +02:00
|
|
|
export function selectForced(
|
|
|
|
req: SelectPayCoinRequestNg,
|
|
|
|
candidateDenoms: AvailableDenom[],
|
|
|
|
): SelResult | undefined {
|
|
|
|
const selectedDenom: SelResult = {};
|
|
|
|
|
|
|
|
const forcedSelection = req.forcedSelection;
|
|
|
|
checkLogicInvariant(!!forcedSelection);
|
|
|
|
|
|
|
|
for (const forcedCoin of forcedSelection.coins) {
|
|
|
|
let found = false;
|
|
|
|
for (const aci of candidateDenoms) {
|
|
|
|
if (aci.numAvailable <= 0) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if (Amounts.cmp(aci.value, forcedCoin.value) === 0) {
|
|
|
|
aci.numAvailable--;
|
2022-09-16 16:20:47 +02:00
|
|
|
const avKey = makeAvailabilityKey(
|
|
|
|
aci.exchangeBaseUrl,
|
|
|
|
aci.denomPubHash,
|
|
|
|
aci.maxAge,
|
|
|
|
);
|
|
|
|
let sd = selectedDenom[avKey];
|
|
|
|
if (!sd) {
|
|
|
|
sd = {
|
|
|
|
contributions: [],
|
|
|
|
denomPubHash: aci.denomPubHash,
|
|
|
|
exchangeBaseUrl: aci.exchangeBaseUrl,
|
|
|
|
maxAge: aci.maxAge,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
sd.contributions.push(Amounts.parseOrThrow(forcedCoin.value));
|
|
|
|
selectedDenom[avKey] = sd;
|
2022-09-15 21:00:36 +02:00
|
|
|
found = true;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!found) {
|
|
|
|
throw Error("can't find coin for forced coin selection");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return selectedDenom;
|
|
|
|
}
|
|
|
|
|
2023-01-05 18:45:49 +01:00
|
|
|
export type SelectPayCoinsResult =
|
|
|
|
| {
|
|
|
|
type: "failure";
|
|
|
|
insufficientBalanceDetails: PayMerchantInsufficientBalanceDetails;
|
|
|
|
}
|
|
|
|
| { type: "success"; coinSel: PayCoinSelection };
|
|
|
|
|
2022-09-15 21:00:36 +02:00
|
|
|
/**
|
|
|
|
* Given a list of candidate coins, select coins to spend under the merchant's
|
|
|
|
* constraints.
|
|
|
|
*
|
|
|
|
* The prevPayCoins can be specified to "repair" a coin selection
|
|
|
|
* by adding additional coins, after a broken (e.g. double-spent) coin
|
|
|
|
* has been removed from the selection.
|
|
|
|
*
|
|
|
|
* This function is only exported for the sake of unit tests.
|
|
|
|
*/
|
|
|
|
export async function selectPayCoinsNew(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
req: SelectPayCoinRequestNg,
|
2023-01-05 18:45:49 +01:00
|
|
|
): Promise<SelectPayCoinsResult> {
|
2022-09-15 21:00:36 +02:00
|
|
|
const {
|
|
|
|
contractTermsAmount,
|
|
|
|
depositFeeLimit,
|
|
|
|
wireFeeLimit,
|
|
|
|
wireFeeAmortization,
|
|
|
|
} = req;
|
|
|
|
|
|
|
|
const [candidateDenoms, wireFeesPerExchange] = await selectCandidates(
|
|
|
|
ws,
|
|
|
|
req,
|
|
|
|
);
|
|
|
|
|
2022-09-21 12:40:02 +02:00
|
|
|
// logger.trace(`candidate denoms: ${j2s(candidateDenoms)}`);
|
|
|
|
|
2022-09-15 21:00:36 +02:00
|
|
|
const coinPubs: string[] = [];
|
|
|
|
const coinContributions: AmountJson[] = [];
|
|
|
|
const currency = contractTermsAmount.currency;
|
|
|
|
|
|
|
|
let tally: CoinSelectionTally = {
|
|
|
|
amountPayRemaining: contractTermsAmount,
|
|
|
|
amountWireFeeLimitRemaining: wireFeeLimit,
|
|
|
|
amountDepositFeeLimitRemaining: depositFeeLimit,
|
2022-11-02 17:42:14 +01:00
|
|
|
customerDepositFees: Amounts.zeroOfCurrency(currency),
|
|
|
|
customerWireFees: Amounts.zeroOfCurrency(currency),
|
2022-09-15 21:00:36 +02:00
|
|
|
wireFeeCoveredForExchange: new Set(),
|
2023-01-05 18:45:49 +01:00
|
|
|
lastDepositFee: Amounts.zeroOfCurrency(currency),
|
2022-09-15 21:00:36 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
const prevPayCoins = req.prevPayCoins ?? [];
|
|
|
|
|
|
|
|
// Look at existing pay coin selection and tally up
|
|
|
|
for (const prev of prevPayCoins) {
|
|
|
|
tally = tallyFees(
|
|
|
|
tally,
|
|
|
|
wireFeesPerExchange,
|
|
|
|
wireFeeAmortization,
|
|
|
|
prev.exchangeBaseUrl,
|
|
|
|
prev.feeDeposit,
|
|
|
|
);
|
|
|
|
tally.amountPayRemaining = Amounts.sub(
|
|
|
|
tally.amountPayRemaining,
|
|
|
|
prev.contribution,
|
|
|
|
).amount;
|
|
|
|
|
|
|
|
coinPubs.push(prev.coinPub);
|
|
|
|
coinContributions.push(prev.contribution);
|
|
|
|
}
|
|
|
|
|
|
|
|
let selectedDenom: SelResult | undefined;
|
|
|
|
if (req.forcedSelection) {
|
|
|
|
selectedDenom = selectForced(req, candidateDenoms);
|
|
|
|
} else {
|
|
|
|
// FIXME: Here, we should select coins in a smarter way.
|
|
|
|
// Instead of always spending the next-largest coin,
|
|
|
|
// we should try to find the smallest coin that covers the
|
|
|
|
// amount.
|
|
|
|
selectedDenom = selectGreedy(
|
|
|
|
req,
|
|
|
|
candidateDenoms,
|
|
|
|
wireFeesPerExchange,
|
|
|
|
tally,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!selectedDenom) {
|
2023-01-05 18:45:49 +01:00
|
|
|
const details = await getMerchantPaymentBalanceDetails(ws, {
|
|
|
|
acceptedAuditors: req.auditors,
|
|
|
|
acceptedExchanges: req.exchanges,
|
|
|
|
acceptedWireMethods: [req.wireMethod],
|
|
|
|
currency: Amounts.currencyOf(req.contractTermsAmount),
|
|
|
|
minAge: req.requiredMinimumAge ?? 0,
|
|
|
|
});
|
|
|
|
let feeGapEstimate: AmountJson;
|
|
|
|
if (
|
|
|
|
Amounts.cmp(
|
|
|
|
details.balanceMerchantDepositable,
|
|
|
|
req.contractTermsAmount,
|
|
|
|
) >= 0
|
|
|
|
) {
|
|
|
|
// FIXME: We can probably give a better estimate.
|
|
|
|
feeGapEstimate = Amounts.add(
|
|
|
|
tally.amountPayRemaining,
|
|
|
|
tally.lastDepositFee,
|
|
|
|
).amount;
|
|
|
|
} else {
|
|
|
|
feeGapEstimate = Amounts.zeroOfAmount(req.contractTermsAmount);
|
|
|
|
}
|
|
|
|
return {
|
|
|
|
type: "failure",
|
|
|
|
insufficientBalanceDetails: {
|
|
|
|
amountRequested: Amounts.stringify(req.contractTermsAmount),
|
|
|
|
balanceAgeAcceptable: Amounts.stringify(details.balanceAgeAcceptable),
|
|
|
|
balanceAvailable: Amounts.stringify(details.balanceAvailable),
|
|
|
|
balanceMaterial: Amounts.stringify(details.balanceMaterial),
|
|
|
|
balanceMerchantAcceptable: Amounts.stringify(
|
|
|
|
details.balanceMerchantAcceptable,
|
|
|
|
),
|
|
|
|
balanceMerchantDepositable: Amounts.stringify(
|
|
|
|
details.balanceMerchantDepositable,
|
|
|
|
),
|
|
|
|
feeGapEstimate: Amounts.stringify(feeGapEstimate),
|
|
|
|
},
|
|
|
|
};
|
2022-09-15 21:00:36 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
const finalSel = selectedDenom;
|
|
|
|
|
2022-09-21 12:40:02 +02:00
|
|
|
logger.trace(`coin selection request ${j2s(req)}`);
|
|
|
|
logger.trace(`selected coins (via denoms) for payment: ${j2s(finalSel)}`);
|
|
|
|
|
2022-09-15 21:00:36 +02:00
|
|
|
await ws.db
|
|
|
|
.mktx((x) => [x.coins, x.denominations])
|
|
|
|
.runReadOnly(async (tx) => {
|
|
|
|
for (const dph of Object.keys(finalSel)) {
|
2022-09-16 16:20:47 +02:00
|
|
|
const selInfo = finalSel[dph];
|
|
|
|
const numRequested = selInfo.contributions.length;
|
|
|
|
const query = [
|
|
|
|
selInfo.exchangeBaseUrl,
|
|
|
|
selInfo.denomPubHash,
|
|
|
|
selInfo.maxAge,
|
|
|
|
CoinStatus.Fresh,
|
|
|
|
];
|
|
|
|
logger.info(`query: ${j2s(query)}`);
|
|
|
|
const coins =
|
|
|
|
await tx.coins.indexes.byExchangeDenomPubHashAndAgeAndStatus.getAll(
|
|
|
|
query,
|
|
|
|
numRequested,
|
|
|
|
);
|
|
|
|
if (coins.length != numRequested) {
|
2022-09-15 21:00:36 +02:00
|
|
|
throw Error(
|
2022-09-16 16:20:47 +02:00
|
|
|
`coin selection failed (not available anymore, got only ${coins.length}/${numRequested})`,
|
2022-09-15 21:00:36 +02:00
|
|
|
);
|
|
|
|
}
|
|
|
|
coinPubs.push(...coins.map((x) => x.coinPub));
|
2022-09-16 16:20:47 +02:00
|
|
|
coinContributions.push(...selInfo.contributions);
|
2022-09-15 21:00:36 +02:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return {
|
2023-01-05 18:45:49 +01:00
|
|
|
type: "success",
|
|
|
|
coinSel: {
|
|
|
|
paymentAmount: Amounts.stringify(contractTermsAmount),
|
|
|
|
coinContributions: coinContributions.map((x) => Amounts.stringify(x)),
|
|
|
|
coinPubs,
|
|
|
|
customerDepositFees: Amounts.stringify(tally.customerDepositFees),
|
|
|
|
customerWireFees: Amounts.stringify(tally.customerWireFees),
|
|
|
|
},
|
2022-09-15 21:00:36 +02:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2021-03-10 17:11:59 +01:00
|
|
|
export async function checkPaymentByProposalId(
|
2019-12-02 00:42:40 +01:00
|
|
|
ws: InternalWalletState,
|
2021-03-10 17:11:59 +01:00
|
|
|
proposalId: string,
|
|
|
|
sessionId?: string,
|
2019-12-02 00:42:40 +01:00
|
|
|
): Promise<PreparePayResult> {
|
2021-06-09 15:14:17 +02:00
|
|
|
let proposal = await ws.db
|
2022-10-08 20:56:57 +02:00
|
|
|
.mktx((x) => [x.purchases])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadOnly(async (tx) => {
|
2022-10-08 20:56:57 +02:00
|
|
|
return tx.purchases.get(proposalId);
|
2021-06-09 15:14:17 +02:00
|
|
|
});
|
2019-12-03 00:52:15 +01:00
|
|
|
if (!proposal) {
|
2022-11-25 16:18:52 +01:00
|
|
|
throw Error(`could not get proposal ${proposalId}`);
|
2019-12-02 00:42:40 +01:00
|
|
|
}
|
2022-10-08 23:45:49 +02:00
|
|
|
if (proposal.purchaseStatus === PurchaseStatus.RepurchaseDetected) {
|
2019-12-03 00:52:15 +01:00
|
|
|
const existingProposalId = proposal.repurchaseProposalId;
|
|
|
|
if (!existingProposalId) {
|
|
|
|
throw Error("invalid proposal state");
|
2019-12-02 00:42:40 +01:00
|
|
|
}
|
2020-08-14 12:23:50 +02:00
|
|
|
logger.trace("using existing purchase for same product");
|
2021-06-09 15:14:17 +02:00
|
|
|
proposal = await ws.db
|
2022-10-08 20:56:57 +02:00
|
|
|
.mktx((x) => [x.purchases])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadOnly(async (tx) => {
|
2022-10-08 20:56:57 +02:00
|
|
|
return tx.purchases.get(existingProposalId);
|
2021-06-09 15:14:17 +02:00
|
|
|
});
|
2019-12-03 00:52:15 +01:00
|
|
|
if (!proposal) {
|
|
|
|
throw Error("existing proposal is in wrong state");
|
|
|
|
}
|
|
|
|
}
|
2022-10-09 02:23:06 +02:00
|
|
|
const d = await expectProposalDownload(ws, proposal);
|
2019-12-19 20:42:49 +01:00
|
|
|
const contractData = d.contractData;
|
|
|
|
const merchantSig = d.contractData.merchantSig;
|
|
|
|
if (!merchantSig) {
|
2019-12-03 00:52:15 +01:00
|
|
|
throw Error("BUG: proposal is in invalid state");
|
2019-12-02 00:42:40 +01:00
|
|
|
}
|
|
|
|
|
2019-12-06 00:56:31 +01:00
|
|
|
proposalId = proposal.proposalId;
|
2019-12-03 00:52:15 +01:00
|
|
|
|
2022-11-25 03:16:01 +01:00
|
|
|
const talerUri = constructPayUri(
|
|
|
|
proposal.merchantBaseUrl,
|
|
|
|
proposal.orderId,
|
|
|
|
proposal.lastSessionId ?? proposal.downloadSessionId ?? "",
|
|
|
|
proposal.claimToken,
|
|
|
|
proposal.noncePriv,
|
|
|
|
);
|
|
|
|
|
2021-04-27 23:42:25 +02:00
|
|
|
// First check if we already paid for it.
|
2021-06-09 15:14:17 +02:00
|
|
|
const purchase = await ws.db
|
2022-09-13 13:25:41 +02:00
|
|
|
.mktx((x) => [x.purchases])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadOnly(async (tx) => {
|
|
|
|
return tx.purchases.get(proposalId);
|
|
|
|
});
|
2019-12-02 00:42:40 +01:00
|
|
|
|
2022-10-08 23:45:49 +02:00
|
|
|
if (!purchase || purchase.purchaseStatus === PurchaseStatus.Proposed) {
|
2019-12-19 20:42:49 +01:00
|
|
|
// If not already paid, check if we could pay for it.
|
2022-09-15 21:00:36 +02:00
|
|
|
const res = await selectPayCoinsNew(ws, {
|
|
|
|
auditors: contractData.allowedAuditors,
|
|
|
|
exchanges: contractData.allowedExchanges,
|
2022-11-02 17:42:14 +01:00
|
|
|
contractTermsAmount: Amounts.parseOrThrow(contractData.amount),
|
|
|
|
depositFeeLimit: Amounts.parseOrThrow(contractData.maxDepositFee),
|
2021-03-15 13:43:53 +01:00
|
|
|
wireFeeAmortization: contractData.wireFeeAmortization ?? 1,
|
2022-11-02 17:42:14 +01:00
|
|
|
wireFeeLimit: Amounts.parseOrThrow(contractData.maxWireFee),
|
2021-03-15 13:43:53 +01:00
|
|
|
prevPayCoins: [],
|
2022-04-29 21:05:17 +02:00
|
|
|
requiredMinimumAge: contractData.minimumAge,
|
2022-09-15 21:00:36 +02:00
|
|
|
wireMethod: contractData.wireMethod,
|
2021-03-15 13:43:53 +01:00
|
|
|
});
|
2019-12-02 00:42:40 +01:00
|
|
|
|
2023-01-05 18:45:49 +01:00
|
|
|
if (res.type !== "success") {
|
2022-09-21 12:40:02 +02:00
|
|
|
logger.info("not allowing payment, insufficient coins");
|
2019-12-02 00:42:40 +01:00
|
|
|
return {
|
2020-07-28 11:48:01 +02:00
|
|
|
status: PreparePayResultType.InsufficientBalance,
|
2020-12-21 13:23:07 +01:00
|
|
|
contractTerms: d.contractTermsRaw,
|
2019-12-02 00:42:40 +01:00
|
|
|
proposalId: proposal.proposalId,
|
2021-09-17 20:48:33 +02:00
|
|
|
noncePriv: proposal.noncePriv,
|
2020-08-10 16:35:41 +02:00
|
|
|
amountRaw: Amounts.stringify(d.contractData.amount),
|
2022-11-25 03:16:01 +01:00
|
|
|
talerUri,
|
2023-01-05 18:45:49 +01:00
|
|
|
balanceDetails: res.insufficientBalanceDetails,
|
2019-12-02 00:42:40 +01:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2023-01-05 18:45:49 +01:00
|
|
|
const totalCost = await getTotalPaymentCost(ws, res.coinSel);
|
2020-09-08 17:15:33 +02:00
|
|
|
logger.trace("costInfo", totalCost);
|
2020-07-29 19:40:41 +02:00
|
|
|
logger.trace("coinsForPayment", res);
|
2019-12-25 19:11:20 +01:00
|
|
|
|
2019-12-02 00:42:40 +01:00
|
|
|
return {
|
2020-07-28 11:48:01 +02:00
|
|
|
status: PreparePayResultType.PaymentPossible,
|
2020-12-21 13:23:07 +01:00
|
|
|
contractTerms: d.contractTermsRaw,
|
2019-12-02 00:42:40 +01:00
|
|
|
proposalId: proposal.proposalId,
|
2021-09-17 20:48:33 +02:00
|
|
|
noncePriv: proposal.noncePriv,
|
2020-09-08 17:15:33 +02:00
|
|
|
amountEffective: Amounts.stringify(totalCost),
|
2023-01-05 18:45:49 +01:00
|
|
|
amountRaw: Amounts.stringify(res.coinSel.paymentAmount),
|
2021-08-06 11:45:08 +02:00
|
|
|
contractTermsHash: d.contractData.contractTermsHash,
|
2022-11-25 03:16:01 +01:00
|
|
|
talerUri,
|
2019-12-02 00:42:40 +01:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2022-10-08 20:56:57 +02:00
|
|
|
if (
|
2022-10-08 23:45:49 +02:00
|
|
|
purchase.purchaseStatus === PurchaseStatus.Paid &&
|
2022-10-08 20:56:57 +02:00
|
|
|
purchase.lastSessionId !== sessionId
|
|
|
|
) {
|
2020-07-29 19:40:41 +02:00
|
|
|
logger.trace(
|
2019-12-19 20:42:49 +01:00
|
|
|
"automatically re-submitting payment with different session ID",
|
|
|
|
);
|
2022-10-08 20:56:57 +02:00
|
|
|
logger.trace(`last: ${purchase.lastSessionId}, current: ${sessionId}`);
|
2021-06-09 15:14:17 +02:00
|
|
|
await ws.db
|
2022-09-13 13:25:41 +02:00
|
|
|
.mktx((x) => [x.purchases])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadWrite(async (tx) => {
|
|
|
|
const p = await tx.purchases.get(proposalId);
|
|
|
|
if (!p) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
p.lastSessionId = sessionId;
|
2022-10-08 23:45:49 +02:00
|
|
|
p.purchaseStatus = PurchaseStatus.PayingReplay;
|
2021-06-09 15:14:17 +02:00
|
|
|
await tx.purchases.put(p);
|
|
|
|
});
|
2022-03-29 13:47:32 +02:00
|
|
|
const r = await processPurchasePay(ws, proposalId, { forceNow: true });
|
2022-09-05 18:12:30 +02:00
|
|
|
if (r.type !== OperationAttemptResultType.Finished) {
|
|
|
|
// FIXME: This does not surface the original error
|
2020-08-11 14:02:11 +02:00
|
|
|
throw Error("submitting pay failed");
|
|
|
|
}
|
2022-10-09 02:23:06 +02:00
|
|
|
const download = await expectProposalDownload(ws, purchase);
|
2020-07-28 11:48:01 +02:00
|
|
|
return {
|
|
|
|
status: PreparePayResultType.AlreadyConfirmed,
|
2022-10-08 20:56:57 +02:00
|
|
|
contractTerms: download.contractTermsRaw,
|
|
|
|
contractTermsHash: download.contractData.contractTermsHash,
|
2020-07-28 11:48:01 +02:00
|
|
|
paid: true,
|
2022-10-08 20:56:57 +02:00
|
|
|
amountRaw: Amounts.stringify(download.contractData.amount),
|
|
|
|
amountEffective: Amounts.stringify(purchase.payInfo?.totalPayCost!),
|
2020-09-03 14:03:11 +02:00
|
|
|
proposalId,
|
2022-11-25 03:16:01 +01:00
|
|
|
talerUri,
|
2020-07-28 11:48:01 +02:00
|
|
|
};
|
|
|
|
} else if (!purchase.timestampFirstSuccessfulPay) {
|
2022-10-09 02:23:06 +02:00
|
|
|
const download = await expectProposalDownload(ws, purchase);
|
2020-07-28 11:48:01 +02:00
|
|
|
return {
|
|
|
|
status: PreparePayResultType.AlreadyConfirmed,
|
2022-10-08 20:56:57 +02:00
|
|
|
contractTerms: download.contractTermsRaw,
|
|
|
|
contractTermsHash: download.contractData.contractTermsHash,
|
2020-07-28 11:48:01 +02:00
|
|
|
paid: false,
|
2022-10-08 20:56:57 +02:00
|
|
|
amountRaw: Amounts.stringify(download.contractData.amount),
|
|
|
|
amountEffective: Amounts.stringify(purchase.payInfo?.totalPayCost!),
|
2020-09-03 14:03:11 +02:00
|
|
|
proposalId,
|
2022-11-25 03:16:01 +01:00
|
|
|
talerUri,
|
2020-07-30 13:58:09 +02:00
|
|
|
};
|
2020-08-12 13:02:07 +02:00
|
|
|
} else {
|
2022-10-08 20:56:57 +02:00
|
|
|
const paid =
|
2022-10-08 23:45:49 +02:00
|
|
|
purchase.purchaseStatus === PurchaseStatus.Paid ||
|
|
|
|
purchase.purchaseStatus === PurchaseStatus.QueryingRefund ||
|
|
|
|
purchase.purchaseStatus === PurchaseStatus.QueryingAutoRefund;
|
2022-10-09 02:23:06 +02:00
|
|
|
const download = await expectProposalDownload(ws, purchase);
|
2020-07-28 11:48:01 +02:00
|
|
|
return {
|
|
|
|
status: PreparePayResultType.AlreadyConfirmed,
|
2022-10-08 20:56:57 +02:00
|
|
|
contractTerms: download.contractTermsRaw,
|
|
|
|
contractTermsHash: download.contractData.contractTermsHash,
|
2020-08-12 13:02:07 +02:00
|
|
|
paid,
|
2022-10-08 20:56:57 +02:00
|
|
|
amountRaw: Amounts.stringify(download.contractData.amount),
|
|
|
|
amountEffective: Amounts.stringify(purchase.payInfo?.totalPayCost!),
|
|
|
|
...(paid ? { nextUrl: download.contractData.orderId } : {}),
|
2020-09-03 14:03:11 +02:00
|
|
|
proposalId,
|
2022-11-25 03:16:01 +01:00
|
|
|
talerUri,
|
2020-07-28 11:48:01 +02:00
|
|
|
};
|
2019-12-02 00:42:40 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-08 18:53:04 +02:00
|
|
|
export async function getContractTermsDetails(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
proposalId: string,
|
|
|
|
): Promise<WalletContractData> {
|
|
|
|
const proposal = await ws.db
|
2022-10-08 20:56:57 +02:00
|
|
|
.mktx((x) => [x.purchases])
|
2022-08-08 18:53:04 +02:00
|
|
|
.runReadOnly(async (tx) => {
|
2022-10-08 20:56:57 +02:00
|
|
|
return tx.purchases.get(proposalId);
|
2022-08-08 18:53:04 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
if (!proposal) {
|
|
|
|
throw Error(`proposal with id ${proposalId} not found`);
|
|
|
|
}
|
|
|
|
|
2022-10-09 02:23:06 +02:00
|
|
|
const d = await expectProposalDownload(ws, proposal);
|
2022-08-08 18:53:04 +02:00
|
|
|
|
2022-10-09 02:23:06 +02:00
|
|
|
return d.contractData;
|
2022-08-08 18:53:04 +02:00
|
|
|
}
|
|
|
|
|
2021-03-10 17:11:59 +01:00
|
|
|
/**
|
|
|
|
* Check if a payment for the given taler://pay/ URI is possible.
|
|
|
|
*
|
|
|
|
* If the payment is possible, the signature are already generated but not
|
|
|
|
* yet send to the merchant.
|
|
|
|
*/
|
|
|
|
export async function preparePayForUri(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
talerPayUri: string,
|
|
|
|
): Promise<PreparePayResult> {
|
|
|
|
const uriResult = parsePayUri(talerPayUri);
|
|
|
|
|
|
|
|
if (!uriResult) {
|
2022-03-22 21:16:38 +01:00
|
|
|
throw TalerError.fromDetail(
|
2021-03-10 17:11:59 +01:00
|
|
|
TalerErrorCode.WALLET_INVALID_TALER_PAY_URI,
|
|
|
|
{
|
|
|
|
talerPayUri,
|
|
|
|
},
|
2022-03-22 21:16:38 +01:00
|
|
|
`invalid taler://pay URI (${talerPayUri})`,
|
2021-03-10 17:11:59 +01:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-11-25 03:16:01 +01:00
|
|
|
const proposalId = await startDownloadProposal(
|
2021-03-10 17:11:59 +01:00
|
|
|
ws,
|
|
|
|
uriResult.merchantBaseUrl,
|
|
|
|
uriResult.orderId,
|
|
|
|
uriResult.sessionId,
|
|
|
|
uriResult.claimToken,
|
2021-09-17 20:48:33 +02:00
|
|
|
uriResult.noncePriv,
|
2021-03-10 17:11:59 +01:00
|
|
|
);
|
|
|
|
|
|
|
|
return checkPaymentByProposalId(ws, proposalId, uriResult.sessionId);
|
|
|
|
}
|
|
|
|
|
2021-01-04 13:30:38 +01:00
|
|
|
/**
|
|
|
|
* Generate deposit permissions for a purchase.
|
|
|
|
*
|
|
|
|
* Accesses the database and the crypto worker.
|
|
|
|
*/
|
2021-01-18 23:35:41 +01:00
|
|
|
export async function generateDepositPermissions(
|
2021-01-04 13:30:38 +01:00
|
|
|
ws: InternalWalletState,
|
|
|
|
payCoinSel: PayCoinSelection,
|
|
|
|
contractData: WalletContractData,
|
|
|
|
): Promise<CoinDepositPermission[]> {
|
|
|
|
const depositPermissions: CoinDepositPermission[] = [];
|
2021-06-09 15:14:17 +02:00
|
|
|
const coinWithDenom: Array<{
|
|
|
|
coin: CoinRecord;
|
|
|
|
denom: DenominationRecord;
|
|
|
|
}> = [];
|
|
|
|
await ws.db
|
2022-09-13 13:25:41 +02:00
|
|
|
.mktx((x) => [x.coins, x.denominations])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadOnly(async (tx) => {
|
|
|
|
for (let i = 0; i < payCoinSel.coinPubs.length; i++) {
|
|
|
|
const coin = await tx.coins.get(payCoinSel.coinPubs[i]);
|
|
|
|
if (!coin) {
|
|
|
|
throw Error("can't pay, allocated coin not found anymore");
|
|
|
|
}
|
|
|
|
const denom = await tx.denominations.get([
|
|
|
|
coin.exchangeBaseUrl,
|
|
|
|
coin.denomPubHash,
|
|
|
|
]);
|
|
|
|
if (!denom) {
|
|
|
|
throw Error(
|
|
|
|
"can't pay, denomination of allocated coin not found anymore",
|
|
|
|
);
|
|
|
|
}
|
|
|
|
coinWithDenom.push({ coin, denom });
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2021-01-04 13:30:38 +01:00
|
|
|
for (let i = 0; i < payCoinSel.coinPubs.length; i++) {
|
2021-06-09 15:14:17 +02:00
|
|
|
const { coin, denom } = coinWithDenom[i];
|
2021-11-27 20:56:58 +01:00
|
|
|
let wireInfoHash: string;
|
2022-02-21 12:40:51 +01:00
|
|
|
wireInfoHash = contractData.wireInfoHash;
|
2022-04-19 17:12:43 +02:00
|
|
|
logger.trace(
|
2022-09-16 16:20:47 +02:00
|
|
|
`signing deposit permission for coin with ageRestriction=${j2s(
|
2022-04-19 17:12:43 +02:00
|
|
|
coin.ageCommitmentProof,
|
|
|
|
)}`,
|
|
|
|
);
|
2021-01-04 13:30:38 +01:00
|
|
|
const dp = await ws.cryptoApi.signDepositPermission({
|
|
|
|
coinPriv: coin.coinPriv,
|
|
|
|
coinPub: coin.coinPub,
|
|
|
|
contractTermsHash: contractData.contractTermsHash,
|
|
|
|
denomPubHash: coin.denomPubHash,
|
2022-03-10 16:30:24 +01:00
|
|
|
denomKeyType: denom.denomPub.cipher,
|
2021-01-04 13:30:38 +01:00
|
|
|
denomSig: coin.denomSig,
|
|
|
|
exchangeBaseUrl: coin.exchangeBaseUrl,
|
2022-11-02 17:42:14 +01:00
|
|
|
feeDeposit: Amounts.parseOrThrow(denom.fees.feeDeposit),
|
2021-01-04 13:30:38 +01:00
|
|
|
merchantPub: contractData.merchantPub,
|
|
|
|
refundDeadline: contractData.refundDeadline,
|
2022-11-02 17:42:14 +01:00
|
|
|
spendAmount: Amounts.parseOrThrow(payCoinSel.coinContributions[i]),
|
2021-01-04 13:30:38 +01:00
|
|
|
timestamp: contractData.timestamp,
|
2021-11-27 20:56:58 +01:00
|
|
|
wireInfoHash,
|
2022-04-19 17:12:43 +02:00
|
|
|
ageCommitmentProof: coin.ageCommitmentProof,
|
|
|
|
requiredMinimumAge: contractData.minimumAge,
|
2021-01-04 13:30:38 +01:00
|
|
|
});
|
|
|
|
depositPermissions.push(dp);
|
|
|
|
}
|
|
|
|
return depositPermissions;
|
|
|
|
}
|
|
|
|
|
2022-09-05 18:12:30 +02:00
|
|
|
/**
|
|
|
|
* Run the operation handler for a payment
|
|
|
|
* and return the result as a {@link ConfirmPayResult}.
|
|
|
|
*/
|
|
|
|
export async function runPayForConfirmPay(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
proposalId: string,
|
|
|
|
): Promise<ConfirmPayResult> {
|
|
|
|
const res = await processPurchasePay(ws, proposalId, { forceNow: true });
|
|
|
|
switch (res.type) {
|
|
|
|
case OperationAttemptResultType.Finished: {
|
|
|
|
const purchase = await ws.db
|
2022-09-13 13:25:41 +02:00
|
|
|
.mktx((x) => [x.purchases])
|
2022-09-05 18:12:30 +02:00
|
|
|
.runReadOnly(async (tx) => {
|
|
|
|
return tx.purchases.get(proposalId);
|
|
|
|
});
|
2022-10-09 02:23:06 +02:00
|
|
|
if (!purchase) {
|
2022-09-05 18:12:30 +02:00
|
|
|
throw Error("purchase record not available anymore");
|
|
|
|
}
|
2022-10-09 02:23:06 +02:00
|
|
|
const d = await expectProposalDownload(ws, purchase);
|
2022-09-05 18:12:30 +02:00
|
|
|
return {
|
|
|
|
type: ConfirmPayResultType.Done,
|
2022-10-09 02:23:06 +02:00
|
|
|
contractTerms: d.contractTermsRaw,
|
2022-10-14 22:47:11 +02:00
|
|
|
transactionId: makeTransactionId(TransactionType.Payment, proposalId),
|
2022-09-05 18:12:30 +02:00
|
|
|
};
|
|
|
|
}
|
2022-09-19 12:13:31 +02:00
|
|
|
case OperationAttemptResultType.Error: {
|
|
|
|
// We hide transient errors from the caller.
|
|
|
|
const opRetry = await ws.db
|
|
|
|
.mktx((x) => [x.operationRetries])
|
|
|
|
.runReadOnly(async (tx) =>
|
|
|
|
tx.operationRetries.get(RetryTags.byPaymentProposalId(proposalId)),
|
|
|
|
);
|
|
|
|
const maxRetry = 3;
|
|
|
|
const numRetry = opRetry?.retryInfo.retryCounter ?? 0;
|
|
|
|
if (
|
|
|
|
res.errorDetail.code ===
|
2022-11-16 20:04:52 +01:00
|
|
|
TalerErrorCode.WALLET_PAY_MERCHANT_SERVER_ERROR &&
|
2022-09-19 12:13:31 +02:00
|
|
|
numRetry < maxRetry
|
|
|
|
) {
|
|
|
|
// Pretend the operation is pending instead of reporting
|
|
|
|
// an error, but only up to maxRetry attempts.
|
|
|
|
await storeOperationPending(
|
|
|
|
ws,
|
|
|
|
RetryTags.byPaymentProposalId(proposalId),
|
|
|
|
);
|
|
|
|
return {
|
|
|
|
type: ConfirmPayResultType.Pending,
|
|
|
|
lastError: opRetry?.lastError,
|
2022-10-14 22:47:11 +02:00
|
|
|
transactionId: makeTransactionId(TransactionType.Payment, proposalId),
|
2022-09-19 12:13:31 +02:00
|
|
|
};
|
|
|
|
} else {
|
|
|
|
// FIXME: allocate error code!
|
|
|
|
await storeOperationError(
|
|
|
|
ws,
|
|
|
|
RetryTags.byPaymentProposalId(proposalId),
|
|
|
|
res.errorDetail,
|
|
|
|
);
|
|
|
|
throw Error("payment failed");
|
|
|
|
}
|
|
|
|
}
|
2022-09-05 18:12:30 +02:00
|
|
|
case OperationAttemptResultType.Pending:
|
2022-10-08 20:56:57 +02:00
|
|
|
await storeOperationPending(
|
|
|
|
ws,
|
|
|
|
`${PendingTaskType.Purchase}:${proposalId}`,
|
|
|
|
);
|
2022-09-05 18:12:30 +02:00
|
|
|
return {
|
|
|
|
type: ConfirmPayResultType.Pending,
|
2022-10-14 22:47:11 +02:00
|
|
|
transactionId: makeTransactionId(TransactionType.Payment, proposalId),
|
2022-09-05 18:12:30 +02:00
|
|
|
lastError: undefined,
|
|
|
|
};
|
|
|
|
case OperationAttemptResultType.Longpoll:
|
|
|
|
throw Error("unexpected processPurchasePay result (longpoll)");
|
|
|
|
default:
|
|
|
|
assertUnreachable(res);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-02 00:42:40 +01:00
|
|
|
/**
|
2022-09-19 12:13:31 +02:00
|
|
|
* Confirm payment for a proposal previously claimed by the wallet.
|
2019-12-02 00:42:40 +01:00
|
|
|
*/
|
|
|
|
export async function confirmPay(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
proposalId: string,
|
2021-01-07 19:50:53 +01:00
|
|
|
sessionIdOverride?: string,
|
2022-06-10 13:03:47 +02:00
|
|
|
forcedCoinSel?: ForcedCoinSel,
|
2019-12-02 00:42:40 +01:00
|
|
|
): Promise<ConfirmPayResult> {
|
|
|
|
logger.trace(
|
|
|
|
`executing confirmPay with proposalId ${proposalId} and sessionIdOverride ${sessionIdOverride}`,
|
|
|
|
);
|
2021-06-09 15:14:17 +02:00
|
|
|
const proposal = await ws.db
|
2022-10-08 20:56:57 +02:00
|
|
|
.mktx((x) => [x.purchases])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadOnly(async (tx) => {
|
2022-10-08 20:56:57 +02:00
|
|
|
return tx.purchases.get(proposalId);
|
2021-06-09 15:14:17 +02:00
|
|
|
});
|
2019-12-02 00:42:40 +01:00
|
|
|
|
|
|
|
if (!proposal) {
|
|
|
|
throw Error(`proposal with id ${proposalId} not found`);
|
|
|
|
}
|
|
|
|
|
2022-10-09 02:23:06 +02:00
|
|
|
const d = await expectProposalDownload(ws, proposal);
|
2019-12-03 00:52:15 +01:00
|
|
|
if (!d) {
|
|
|
|
throw Error("proposal is in invalid state");
|
|
|
|
}
|
|
|
|
|
2021-06-09 15:14:17 +02:00
|
|
|
const existingPurchase = await ws.db
|
2022-09-13 13:25:41 +02:00
|
|
|
.mktx((x) => [x.purchases])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadWrite(async (tx) => {
|
|
|
|
const purchase = await tx.purchases.get(proposalId);
|
|
|
|
if (
|
|
|
|
purchase &&
|
|
|
|
sessionIdOverride !== undefined &&
|
|
|
|
sessionIdOverride != purchase.lastSessionId
|
|
|
|
) {
|
|
|
|
logger.trace(`changing session ID to ${sessionIdOverride}`);
|
|
|
|
purchase.lastSessionId = sessionIdOverride;
|
2022-10-08 23:45:49 +02:00
|
|
|
if (purchase.purchaseStatus === PurchaseStatus.Paid) {
|
|
|
|
purchase.purchaseStatus = PurchaseStatus.PayingReplay;
|
|
|
|
}
|
2021-06-09 15:14:17 +02:00
|
|
|
await tx.purchases.put(purchase);
|
|
|
|
}
|
|
|
|
return purchase;
|
|
|
|
});
|
2019-12-02 00:42:40 +01:00
|
|
|
|
2022-10-08 20:56:57 +02:00
|
|
|
if (existingPurchase && existingPurchase.payInfo) {
|
2019-12-10 12:22:29 +01:00
|
|
|
logger.trace("confirmPay: submitting payment for existing purchase");
|
2022-09-05 18:12:30 +02:00
|
|
|
return runPayForConfirmPay(ws, proposalId);
|
2019-12-02 00:42:40 +01:00
|
|
|
}
|
|
|
|
|
2019-12-10 12:22:29 +01:00
|
|
|
logger.trace("confirmPay: purchase record does not exist yet");
|
|
|
|
|
2021-03-15 13:43:53 +01:00
|
|
|
const contractData = d.contractData;
|
|
|
|
|
2023-01-05 18:45:49 +01:00
|
|
|
let selectCoinsResult: SelectPayCoinsResult | undefined = undefined;
|
2022-06-10 13:03:47 +02:00
|
|
|
|
2023-01-05 18:45:49 +01:00
|
|
|
selectCoinsResult = await selectPayCoinsNew(ws, {
|
2022-09-15 21:00:36 +02:00
|
|
|
auditors: contractData.allowedAuditors,
|
|
|
|
exchanges: contractData.allowedExchanges,
|
|
|
|
wireMethod: contractData.wireMethod,
|
2022-11-02 17:42:14 +01:00
|
|
|
contractTermsAmount: Amounts.parseOrThrow(contractData.amount),
|
|
|
|
depositFeeLimit: Amounts.parseOrThrow(contractData.maxDepositFee),
|
2022-09-15 21:00:36 +02:00
|
|
|
wireFeeAmortization: contractData.wireFeeAmortization ?? 1,
|
2022-11-02 17:42:14 +01:00
|
|
|
wireFeeLimit: Amounts.parseOrThrow(contractData.maxWireFee),
|
2022-09-15 21:00:36 +02:00
|
|
|
prevPayCoins: [],
|
|
|
|
requiredMinimumAge: contractData.minimumAge,
|
|
|
|
forcedSelection: forcedCoinSel,
|
|
|
|
});
|
2019-12-02 00:42:40 +01:00
|
|
|
|
2023-01-05 18:45:49 +01:00
|
|
|
logger.trace("coin selection result", selectCoinsResult);
|
2019-12-02 00:42:40 +01:00
|
|
|
|
2023-01-05 18:45:49 +01:00
|
|
|
if (selectCoinsResult.type === "failure") {
|
2019-12-02 00:42:40 +01:00
|
|
|
// Should not happen, since checkPay should be called first
|
2021-03-15 13:43:53 +01:00
|
|
|
// FIXME: Actually, this should be handled gracefully,
|
|
|
|
// and the status should be stored in the DB.
|
2020-07-30 13:58:09 +02:00
|
|
|
logger.warn("not confirming payment, insufficient coins");
|
2019-12-02 00:42:40 +01:00
|
|
|
throw Error("insufficient balance");
|
|
|
|
}
|
|
|
|
|
2023-01-05 18:45:49 +01:00
|
|
|
const coinSelection = selectCoinsResult.coinSel;
|
2022-10-08 20:56:57 +02:00
|
|
|
const payCostInfo = await getTotalPaymentCost(ws, coinSelection);
|
|
|
|
|
|
|
|
let sessionId: string | undefined;
|
|
|
|
if (sessionIdOverride) {
|
|
|
|
sessionId = sessionIdOverride;
|
|
|
|
} else {
|
|
|
|
sessionId = proposal.downloadSessionId;
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.trace(
|
|
|
|
`recording payment on ${proposal.orderId} with session ID ${sessionId}`,
|
2019-12-15 21:40:06 +01:00
|
|
|
);
|
2019-12-02 00:42:40 +01:00
|
|
|
|
2022-10-08 20:56:57 +02:00
|
|
|
await ws.db
|
|
|
|
.mktx((x) => [
|
|
|
|
x.purchases,
|
|
|
|
x.coins,
|
|
|
|
x.refreshGroups,
|
|
|
|
x.denominations,
|
|
|
|
x.coinAvailability,
|
|
|
|
])
|
|
|
|
.runReadWrite(async (tx) => {
|
|
|
|
const p = await tx.purchases.get(proposal.proposalId);
|
|
|
|
if (!p) {
|
|
|
|
return;
|
|
|
|
}
|
2022-10-08 23:45:49 +02:00
|
|
|
switch (p.purchaseStatus) {
|
|
|
|
case PurchaseStatus.Proposed:
|
2022-10-08 20:56:57 +02:00
|
|
|
p.payInfo = {
|
|
|
|
payCoinSelection: coinSelection,
|
|
|
|
payCoinSelectionUid: encodeCrock(getRandomBytes(16)),
|
2022-11-02 17:42:14 +01:00
|
|
|
totalPayCost: Amounts.stringify(payCostInfo),
|
2022-10-08 20:56:57 +02:00
|
|
|
};
|
|
|
|
p.lastSessionId = sessionId;
|
|
|
|
p.timestampAccept = TalerProtocolTimestamp.now();
|
2022-10-08 23:45:49 +02:00
|
|
|
p.purchaseStatus = PurchaseStatus.Paying;
|
2022-10-08 20:56:57 +02:00
|
|
|
await tx.purchases.put(p);
|
|
|
|
await spendCoins(ws, tx, {
|
2022-10-14 22:47:11 +02:00
|
|
|
allocationId: `txn:proposal:${p.proposalId}`,
|
2022-10-08 20:56:57 +02:00
|
|
|
coinPubs: coinSelection.coinPubs,
|
2022-11-02 17:42:14 +01:00
|
|
|
contributions: coinSelection.coinContributions.map((x) =>
|
|
|
|
Amounts.parseOrThrow(x),
|
|
|
|
),
|
2022-10-08 20:56:57 +02:00
|
|
|
refreshReason: RefreshReason.PayMerchant,
|
|
|
|
});
|
|
|
|
break;
|
2022-10-08 23:45:49 +02:00
|
|
|
case PurchaseStatus.Paid:
|
|
|
|
case PurchaseStatus.Paying:
|
2022-10-08 20:56:57 +02:00
|
|
|
default:
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
ws.notify({
|
|
|
|
type: NotificationType.ProposalAccepted,
|
|
|
|
proposalId: proposal.proposalId,
|
|
|
|
});
|
|
|
|
|
2022-09-05 18:12:30 +02:00
|
|
|
return runPayForConfirmPay(ws, proposalId);
|
2019-12-02 00:42:40 +01:00
|
|
|
}
|
2019-12-03 14:40:05 +01:00
|
|
|
|
2022-10-08 20:56:57 +02:00
|
|
|
export async function processPurchase(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
proposalId: string,
|
|
|
|
options: {
|
|
|
|
forceNow?: boolean;
|
|
|
|
} = {},
|
|
|
|
): Promise<OperationAttemptResult> {
|
|
|
|
const purchase = await ws.db
|
|
|
|
.mktx((x) => [x.purchases])
|
|
|
|
.runReadOnly(async (tx) => {
|
|
|
|
return tx.purchases.get(proposalId);
|
|
|
|
});
|
|
|
|
if (!purchase) {
|
|
|
|
return {
|
|
|
|
type: OperationAttemptResultType.Error,
|
|
|
|
errorDetail: {
|
|
|
|
// FIXME: allocate more specific error code
|
|
|
|
code: TalerErrorCode.WALLET_UNEXPECTED_EXCEPTION,
|
|
|
|
hint: `trying to pay for purchase that is not in the database`,
|
|
|
|
proposalId: proposalId,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2022-10-08 23:45:49 +02:00
|
|
|
switch (purchase.purchaseStatus) {
|
|
|
|
case PurchaseStatus.DownloadingProposal:
|
2022-10-08 20:56:57 +02:00
|
|
|
return processDownloadProposal(ws, proposalId, options);
|
2022-10-08 23:45:49 +02:00
|
|
|
case PurchaseStatus.Paying:
|
|
|
|
case PurchaseStatus.PayingReplay:
|
2022-10-08 20:56:57 +02:00
|
|
|
return processPurchasePay(ws, proposalId, options);
|
2022-10-08 23:45:49 +02:00
|
|
|
case PurchaseStatus.QueryingRefund:
|
|
|
|
case PurchaseStatus.QueryingAutoRefund:
|
|
|
|
case PurchaseStatus.AbortingWithRefund:
|
2022-10-08 20:56:57 +02:00
|
|
|
return processPurchaseQueryRefund(ws, proposalId, options);
|
2022-10-08 23:45:49 +02:00
|
|
|
case PurchaseStatus.ProposalDownloadFailed:
|
|
|
|
case PurchaseStatus.Paid:
|
|
|
|
case PurchaseStatus.RepurchaseDetected:
|
2022-10-12 20:06:45 +02:00
|
|
|
case PurchaseStatus.Proposed:
|
|
|
|
case PurchaseStatus.ProposalRefused:
|
|
|
|
case PurchaseStatus.PaymentAbortFinished:
|
2022-10-08 20:56:57 +02:00
|
|
|
return {
|
|
|
|
type: OperationAttemptResultType.Finished,
|
|
|
|
result: undefined,
|
|
|
|
};
|
|
|
|
default:
|
2022-10-12 20:06:45 +02:00
|
|
|
assertUnreachable(purchase.purchaseStatus);
|
|
|
|
// throw Error(`unexpected purchase status (${purchase.purchaseStatus})`);
|
2022-10-08 20:56:57 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-06 00:24:34 +01:00
|
|
|
export async function processPurchasePay(
|
2019-12-05 19:38:19 +01:00
|
|
|
ws: InternalWalletState,
|
|
|
|
proposalId: string,
|
2022-03-29 13:47:32 +02:00
|
|
|
options: {
|
|
|
|
forceNow?: boolean;
|
|
|
|
} = {},
|
2022-09-05 18:12:30 +02:00
|
|
|
): Promise<OperationAttemptResult> {
|
2021-06-09 15:14:17 +02:00
|
|
|
const purchase = await ws.db
|
2022-09-13 13:25:41 +02:00
|
|
|
.mktx((x) => [x.purchases])
|
2021-06-09 15:14:17 +02:00
|
|
|
.runReadOnly(async (tx) => {
|
|
|
|
return tx.purchases.get(proposalId);
|
|
|
|
});
|
2019-12-05 19:38:19 +01:00
|
|
|
if (!purchase) {
|
2022-03-08 23:09:20 +01:00
|
|
|
return {
|
2022-09-05 18:12:30 +02:00
|
|
|
type: OperationAttemptResultType.Error,
|
|
|
|
errorDetail: {
|
2022-03-08 23:09:20 +01:00
|
|
|
// FIXME: allocate more specific error code
|
|
|
|
code: TalerErrorCode.WALLET_UNEXPECTED_EXCEPTION,
|
2022-03-22 21:16:38 +01:00
|
|
|
hint: `trying to pay for purchase that is not in the database`,
|
|
|
|
proposalId: proposalId,
|
2022-03-08 23:09:20 +01:00
|
|
|
},
|
|
|
|
};
|
2019-12-05 19:38:19 +01:00
|
|
|
}
|
2022-10-08 23:45:49 +02:00
|
|
|
switch (purchase.purchaseStatus) {
|
|
|
|
case PurchaseStatus.Paying:
|
|
|
|
case PurchaseStatus.PayingReplay:
|
2022-10-08 20:56:57 +02:00
|
|
|
break;
|
|
|
|
default:
|
|
|
|
return OperationAttemptResult.finishedEmpty();
|
2022-03-08 23:09:20 +01:00
|
|
|
}
|
2019-12-10 12:22:29 +01:00
|
|
|
logger.trace(`processing purchase pay ${proposalId}`);
|
2022-03-08 23:09:20 +01:00
|
|
|
|
|
|
|
const sessionId = purchase.lastSessionId;
|
|
|
|
|
2022-10-08 20:56:57 +02:00
|
|
|
logger.trace(`paying with session ID ${sessionId}`);
|
|
|
|
const payInfo = purchase.payInfo;
|
|
|
|
checkDbInvariant(!!payInfo, "payInfo");
|
2022-03-08 23:09:20 +01:00
|
|
|
|
2022-10-09 02:23:06 +02:00
|
|
|
const download = await expectProposalDownload(ws, purchase);
|
2022-03-08 23:09:20 +01:00
|
|
|
if (!purchase.merchantPaySig) {
|
|
|
|
const payUrl = new URL(
|
2022-10-08 20:56:57 +02:00
|
|
|
`orders/${download.contractData.orderId}/pay`,
|
|
|
|
download.contractData.merchantBaseUrl,
|
2022-03-08 23:09:20 +01:00
|
|
|
).href;
|
|
|
|
|
|
|
|
let depositPermissions: CoinDepositPermission[];
|
2022-10-14 22:38:40 +02:00
|
|
|
// FIXME: Cache!
|
|
|
|
depositPermissions = await generateDepositPermissions(
|
|
|
|
ws,
|
|
|
|
payInfo.payCoinSelection,
|
|
|
|
download.contractData,
|
|
|
|
);
|
2022-03-08 23:09:20 +01:00
|
|
|
|
|
|
|
const reqBody = {
|
|
|
|
coins: depositPermissions,
|
|
|
|
session_id: purchase.lastSessionId,
|
|
|
|
};
|
|
|
|
|
|
|
|
logger.trace(
|
|
|
|
"making pay request ... ",
|
|
|
|
JSON.stringify(reqBody, undefined, 2),
|
|
|
|
);
|
|
|
|
|
|
|
|
const resp = await ws.runSequentialized([EXCHANGE_COINS_LOCK], () =>
|
|
|
|
ws.http.postJson(payUrl, reqBody, {
|
|
|
|
timeout: getPayRequestTimeout(purchase),
|
|
|
|
}),
|
|
|
|
);
|
|
|
|
|
|
|
|
logger.trace(`got resp ${JSON.stringify(resp)}`);
|
2022-09-19 12:13:31 +02:00
|
|
|
|
|
|
|
if (resp.status >= 500 && resp.status <= 599) {
|
|
|
|
const errDetails = await readUnexpectedResponseDetails(resp);
|
|
|
|
return {
|
|
|
|
type: OperationAttemptResultType.Error,
|
|
|
|
errorDetail: makeErrorDetail(
|
|
|
|
TalerErrorCode.WALLET_PAY_MERCHANT_SERVER_ERROR,
|
|
|
|
{
|
|
|
|
requestError: errDetails,
|
|
|
|
},
|
|
|
|
),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2022-03-08 23:09:20 +01:00
|
|
|
if (resp.status === HttpStatusCode.BadRequest) {
|
|
|
|
const errDetails = await readUnexpectedResponseDetails(resp);
|
|
|
|
logger.warn("unexpected 400 response for /pay");
|
|
|
|
logger.warn(j2s(errDetails));
|
|
|
|
await ws.db
|
2022-09-13 13:25:41 +02:00
|
|
|
.mktx((x) => [x.purchases])
|
2022-03-08 23:09:20 +01:00
|
|
|
.runReadWrite(async (tx) => {
|
|
|
|
const purch = await tx.purchases.get(proposalId);
|
|
|
|
if (!purch) {
|
|
|
|
return;
|
|
|
|
}
|
2022-10-08 20:56:57 +02:00
|
|
|
// FIXME: Should be some "PayPermanentlyFailed" and error info should be stored
|
2022-10-08 23:45:49 +02:00
|
|
|
purch.purchaseStatus = PurchaseStatus.PaymentAbortFinished;
|
2022-03-08 23:09:20 +01:00
|
|
|
await tx.purchases.put(purch);
|
|
|
|
});
|
2022-03-22 21:16:38 +01:00
|
|
|
throw makePendingOperationFailedError(
|
|
|
|
errDetails,
|
|
|
|
TransactionType.Payment,
|
|
|
|
proposalId,
|
|
|
|
);
|
2022-03-08 23:09:20 +01:00
|
|
|
}
|
|
|
|
|
2022-11-25 03:16:01 +01:00
|
|
|
if (resp.status === HttpStatusCode.Gone) {
|
|
|
|
const errDetails = await readUnexpectedResponseDetails(resp);
|
|
|
|
logger.warn("unexpected 410 response for /pay");
|
|
|
|
logger.warn(j2s(errDetails));
|
|
|
|
await ws.db
|
|
|
|
.mktx((x) => [x.purchases])
|
|
|
|
.runReadWrite(async (tx) => {
|
|
|
|
const purch = await tx.purchases.get(proposalId);
|
|
|
|
if (!purch) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
// FIXME: Should be some "PayPermanentlyFailed" and error info should be stored
|
|
|
|
purch.purchaseStatus = PurchaseStatus.PaymentAbortFinished;
|
|
|
|
await tx.purchases.put(purch);
|
|
|
|
});
|
|
|
|
throw makePendingOperationFailedError(
|
|
|
|
errDetails,
|
|
|
|
TransactionType.Payment,
|
|
|
|
proposalId,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-03-08 23:09:20 +01:00
|
|
|
if (resp.status === HttpStatusCode.Conflict) {
|
|
|
|
const err = await readTalerErrorResponse(resp);
|
|
|
|
if (
|
|
|
|
err.code ===
|
|
|
|
TalerErrorCode.MERCHANT_POST_ORDERS_ID_PAY_INSUFFICIENT_FUNDS
|
|
|
|
) {
|
|
|
|
// Do this in the background, as it might take some time
|
|
|
|
handleInsufficientFunds(ws, proposalId, err).catch(async (e) => {
|
2022-09-05 18:12:30 +02:00
|
|
|
console.log("handling insufficient funds failed");
|
|
|
|
|
|
|
|
await scheduleRetry(ws, RetryTags.forPay(purchase), {
|
2022-03-08 23:09:20 +01:00
|
|
|
code: TalerErrorCode.WALLET_UNEXPECTED_EXCEPTION,
|
|
|
|
message: "unexpected exception",
|
|
|
|
hint: "unexpected exception",
|
|
|
|
details: {
|
|
|
|
exception: e.toString(),
|
|
|
|
},
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
return {
|
2022-09-05 18:12:30 +02:00
|
|
|
type: OperationAttemptResultType.Pending,
|
|
|
|
result: undefined,
|
2022-03-08 23:09:20 +01:00
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const merchantResp = await readSuccessResponseJsonOrThrow(
|
|
|
|
resp,
|
|
|
|
codecForMerchantPayResponse(),
|
|
|
|
);
|
|
|
|
|
|
|
|
logger.trace("got success from pay URL", merchantResp);
|
|
|
|
|
2022-10-08 20:56:57 +02:00
|
|
|
const merchantPub = download.contractData.merchantPub;
|
2022-03-23 21:24:23 +01:00
|
|
|
const { valid } = await ws.cryptoApi.isValidPaymentSignature({
|
2022-10-08 20:56:57 +02:00
|
|
|
contractHash: download.contractData.contractTermsHash,
|
2022-03-08 23:09:20 +01:00
|
|
|
merchantPub,
|
2022-03-23 21:24:23 +01:00
|
|
|
sig: merchantResp.sig,
|
|
|
|
});
|
2022-03-08 23:09:20 +01:00
|
|
|
|
|
|
|
if (!valid) {
|
|
|
|
logger.error("merchant payment signature invalid");
|
|
|
|
// FIXME: properly display error
|
|
|
|
throw Error("merchant payment signature invalid");
|
|
|
|
}
|
|
|
|
|
|
|
|
await storeFirstPaySuccess(ws, proposalId, sessionId, merchantResp.sig);
|
|
|
|
await unblockBackup(ws, proposalId);
|
|
|
|
} else {
|
|
|
|
const payAgainUrl = new URL(
|
2022-10-08 20:56:57 +02:00
|
|
|
`orders/${download.contractData.orderId}/paid`,
|
|
|
|
download.contractData.merchantBaseUrl,
|
2022-03-08 23:09:20 +01:00
|
|
|
).href;
|
|
|
|
const reqBody = {
|
|
|
|
sig: purchase.merchantPaySig,
|
2022-10-08 20:56:57 +02:00
|
|
|
h_contract: download.contractData.contractTermsHash,
|
2022-03-08 23:09:20 +01:00
|
|
|
session_id: sessionId ?? "",
|
|
|
|
};
|
2022-10-08 20:56:57 +02:00
|
|
|
logger.trace(`/paid request body: ${j2s(reqBody)}`);
|
2022-03-08 23:09:20 +01:00
|
|
|
const resp = await ws.runSequentialized([EXCHANGE_COINS_LOCK], () =>
|
|
|
|
ws.http.postJson(payAgainUrl, reqBody),
|
|
|
|
);
|
2022-10-08 20:56:57 +02:00
|
|
|
logger.trace(`/paid response status: ${resp.status}`);
|
2022-03-08 23:09:20 +01:00
|
|
|
if (resp.status !== 204) {
|
2022-03-22 21:16:38 +01:00
|
|
|
throw TalerError.fromDetail(
|
2022-03-08 23:09:20 +01:00
|
|
|
TalerErrorCode.WALLET_UNEXPECTED_REQUEST_ERROR,
|
|
|
|
getHttpResponseErrorDetails(resp),
|
2022-03-22 21:16:38 +01:00
|
|
|
"/paid failed",
|
2022-03-08 23:09:20 +01:00
|
|
|
);
|
|
|
|
}
|
|
|
|
await storePayReplaySuccess(ws, proposalId, sessionId);
|
|
|
|
await unblockBackup(ws, proposalId);
|
|
|
|
}
|
|
|
|
|
|
|
|
ws.notify({
|
|
|
|
type: NotificationType.PayOperationSuccess,
|
|
|
|
proposalId: purchase.proposalId,
|
|
|
|
});
|
|
|
|
|
2022-09-05 18:12:30 +02:00
|
|
|
return OperationAttemptResult.finishedEmpty();
|
2019-12-06 00:24:34 +01:00
|
|
|
}
|
2019-12-20 01:25:22 +01:00
|
|
|
|
2019-12-25 19:11:20 +01:00
|
|
|
export async function refuseProposal(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
proposalId: string,
|
2020-04-06 20:02:01 +02:00
|
|
|
): Promise<void> {
|
2021-06-09 15:26:18 +02:00
|
|
|
const success = await ws.db
|
2022-10-08 20:56:57 +02:00
|
|
|
.mktx((x) => [x.purchases])
|
2021-06-09 15:26:18 +02:00
|
|
|
.runReadWrite(async (tx) => {
|
2022-10-08 20:56:57 +02:00
|
|
|
const proposal = await tx.purchases.get(proposalId);
|
2019-12-25 19:11:20 +01:00
|
|
|
if (!proposal) {
|
|
|
|
logger.trace(`proposal ${proposalId} not found, won't refuse proposal`);
|
|
|
|
return false;
|
|
|
|
}
|
2022-10-08 23:45:49 +02:00
|
|
|
if (proposal.purchaseStatus !== PurchaseStatus.Proposed) {
|
2019-12-25 19:11:20 +01:00
|
|
|
return false;
|
|
|
|
}
|
2022-10-08 23:45:49 +02:00
|
|
|
proposal.purchaseStatus = PurchaseStatus.ProposalRefused;
|
2022-10-08 20:56:57 +02:00
|
|
|
await tx.purchases.put(proposal);
|
2019-12-25 19:11:20 +01:00
|
|
|
return true;
|
2021-06-09 15:26:18 +02:00
|
|
|
});
|
2019-12-20 01:25:22 +01:00
|
|
|
if (success) {
|
|
|
|
ws.notify({
|
2020-07-20 12:50:32 +02:00
|
|
|
type: NotificationType.ProposalRefused,
|
2019-12-20 01:25:22 +01:00
|
|
|
});
|
|
|
|
}
|
2019-12-25 19:11:20 +01:00
|
|
|
}
|
2022-10-08 20:56:57 +02:00
|
|
|
|
|
|
|
export async function prepareRefund(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
talerRefundUri: string,
|
|
|
|
): Promise<PrepareRefundResult> {
|
|
|
|
const parseResult = parseRefundUri(talerRefundUri);
|
|
|
|
|
|
|
|
logger.trace("preparing refund offer", parseResult);
|
|
|
|
|
|
|
|
if (!parseResult) {
|
|
|
|
throw Error("invalid refund URI");
|
|
|
|
}
|
|
|
|
|
|
|
|
const purchase = await ws.db
|
|
|
|
.mktx((x) => [x.purchases])
|
|
|
|
.runReadOnly(async (tx) => {
|
2022-10-09 02:23:06 +02:00
|
|
|
return tx.purchases.indexes.byUrlAndOrderId.get([
|
2022-10-08 20:56:57 +02:00
|
|
|
parseResult.merchantBaseUrl,
|
|
|
|
parseResult.orderId,
|
|
|
|
]);
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!purchase) {
|
|
|
|
throw Error(
|
|
|
|
`no purchase for the taler://refund/ URI (${talerRefundUri}) was found`,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
const awaiting = await queryAndSaveAwaitingRefund(ws, purchase);
|
2022-10-09 02:23:06 +02:00
|
|
|
const summary = await calculateRefundSummary(ws, purchase);
|
2022-10-08 20:56:57 +02:00
|
|
|
const proposalId = purchase.proposalId;
|
|
|
|
|
2022-10-09 02:23:06 +02:00
|
|
|
const { contractData: c } = await expectProposalDownload(ws, purchase);
|
2022-10-08 20:56:57 +02:00
|
|
|
|
|
|
|
return {
|
|
|
|
proposalId,
|
|
|
|
effectivePaid: Amounts.stringify(summary.amountEffectivePaid),
|
|
|
|
gone: Amounts.stringify(summary.amountRefundGone),
|
|
|
|
granted: Amounts.stringify(summary.amountRefundGranted),
|
|
|
|
pending: summary.pendingAtExchange,
|
|
|
|
awaiting: Amounts.stringify(awaiting),
|
|
|
|
info: {
|
|
|
|
contractTermsHash: c.contractTermsHash,
|
|
|
|
merchant: c.merchant,
|
|
|
|
orderId: c.orderId,
|
|
|
|
products: c.products,
|
|
|
|
summary: c.summary,
|
|
|
|
fulfillmentMessage: c.fulfillmentMessage,
|
|
|
|
summary_i18n: c.summaryI18n,
|
|
|
|
fulfillmentMessage_i18n: c.fulfillmentMessageI18n,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
function getRefundKey(d: MerchantCoinRefundStatus): string {
|
|
|
|
return `${d.coin_pub}-${d.rtransaction_id}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
async function applySuccessfulRefund(
|
|
|
|
tx: GetReadWriteAccess<{
|
|
|
|
coins: typeof WalletStoresV1.coins;
|
|
|
|
denominations: typeof WalletStoresV1.denominations;
|
|
|
|
}>,
|
|
|
|
p: PurchaseRecord,
|
2022-10-15 11:52:07 +02:00
|
|
|
refreshCoinsMap: Record<string, CoinRefreshRequest>,
|
2022-10-08 20:56:57 +02:00
|
|
|
r: MerchantCoinRefundSuccessStatus,
|
|
|
|
): Promise<void> {
|
|
|
|
// FIXME: check signature before storing it as valid!
|
|
|
|
|
|
|
|
const refundKey = getRefundKey(r);
|
|
|
|
const coin = await tx.coins.get(r.coin_pub);
|
|
|
|
if (!coin) {
|
|
|
|
logger.warn("coin not found, can't apply refund");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const denom = await tx.denominations.get([
|
|
|
|
coin.exchangeBaseUrl,
|
|
|
|
coin.denomPubHash,
|
|
|
|
]);
|
|
|
|
if (!denom) {
|
|
|
|
throw Error("inconsistent database");
|
|
|
|
}
|
|
|
|
const refundAmount = Amounts.parseOrThrow(r.refund_amount);
|
|
|
|
const refundFee = denom.fees.feeRefund;
|
2022-10-15 11:52:07 +02:00
|
|
|
const amountLeft = Amounts.sub(refundAmount, refundFee).amount;
|
2022-10-08 20:56:57 +02:00
|
|
|
coin.status = CoinStatus.Dormant;
|
|
|
|
await tx.coins.put(coin);
|
|
|
|
|
|
|
|
const allDenoms = await tx.denominations.indexes.byExchangeBaseUrl
|
|
|
|
.iter(coin.exchangeBaseUrl)
|
|
|
|
.toArray();
|
|
|
|
const totalRefreshCostBound = getTotalRefreshCost(
|
|
|
|
allDenoms,
|
|
|
|
DenominationRecord.toDenomInfo(denom),
|
|
|
|
amountLeft,
|
|
|
|
);
|
|
|
|
|
2022-11-02 17:42:14 +01:00
|
|
|
refreshCoinsMap[coin.coinPub] = {
|
|
|
|
coinPub: coin.coinPub,
|
|
|
|
amount: Amounts.stringify(amountLeft),
|
|
|
|
};
|
2022-10-15 11:52:07 +02:00
|
|
|
|
2022-10-08 20:56:57 +02:00
|
|
|
p.refunds[refundKey] = {
|
|
|
|
type: RefundState.Applied,
|
|
|
|
obtainedTime: AbsoluteTime.toTimestamp(AbsoluteTime.now()),
|
|
|
|
executionTime: r.execution_time,
|
2022-11-02 17:42:14 +01:00
|
|
|
refundAmount: Amounts.stringify(r.refund_amount),
|
|
|
|
refundFee: Amounts.stringify(denom.fees.feeRefund),
|
|
|
|
totalRefreshCostBound: Amounts.stringify(totalRefreshCostBound),
|
2022-10-08 20:56:57 +02:00
|
|
|
coinPub: r.coin_pub,
|
|
|
|
rtransactionId: r.rtransaction_id,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
async function storePendingRefund(
|
|
|
|
tx: GetReadWriteAccess<{
|
|
|
|
denominations: typeof WalletStoresV1.denominations;
|
|
|
|
coins: typeof WalletStoresV1.coins;
|
|
|
|
}>,
|
|
|
|
p: PurchaseRecord,
|
|
|
|
r: MerchantCoinRefundFailureStatus,
|
|
|
|
): Promise<void> {
|
|
|
|
const refundKey = getRefundKey(r);
|
|
|
|
|
|
|
|
const coin = await tx.coins.get(r.coin_pub);
|
|
|
|
if (!coin) {
|
|
|
|
logger.warn("coin not found, can't apply refund");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const denom = await tx.denominations.get([
|
|
|
|
coin.exchangeBaseUrl,
|
|
|
|
coin.denomPubHash,
|
|
|
|
]);
|
|
|
|
|
|
|
|
if (!denom) {
|
|
|
|
throw Error("inconsistent database");
|
|
|
|
}
|
|
|
|
|
|
|
|
const allDenoms = await tx.denominations.indexes.byExchangeBaseUrl
|
|
|
|
.iter(coin.exchangeBaseUrl)
|
|
|
|
.toArray();
|
|
|
|
|
2022-10-15 11:52:07 +02:00
|
|
|
// Refunded amount after fees.
|
2022-10-08 20:56:57 +02:00
|
|
|
const amountLeft = Amounts.sub(
|
2022-10-15 11:52:07 +02:00
|
|
|
Amounts.parseOrThrow(r.refund_amount),
|
2022-10-08 20:56:57 +02:00
|
|
|
denom.fees.feeRefund,
|
|
|
|
).amount;
|
|
|
|
|
|
|
|
const totalRefreshCostBound = getTotalRefreshCost(
|
|
|
|
allDenoms,
|
|
|
|
DenominationRecord.toDenomInfo(denom),
|
|
|
|
amountLeft,
|
|
|
|
);
|
|
|
|
|
|
|
|
p.refunds[refundKey] = {
|
|
|
|
type: RefundState.Pending,
|
|
|
|
obtainedTime: AbsoluteTime.toTimestamp(AbsoluteTime.now()),
|
|
|
|
executionTime: r.execution_time,
|
2022-11-02 17:42:14 +01:00
|
|
|
refundAmount: Amounts.stringify(r.refund_amount),
|
|
|
|
refundFee: Amounts.stringify(denom.fees.feeRefund),
|
|
|
|
totalRefreshCostBound: Amounts.stringify(totalRefreshCostBound),
|
2022-10-08 20:56:57 +02:00
|
|
|
coinPub: r.coin_pub,
|
|
|
|
rtransactionId: r.rtransaction_id,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
async function storeFailedRefund(
|
|
|
|
tx: GetReadWriteAccess<{
|
|
|
|
coins: typeof WalletStoresV1.coins;
|
|
|
|
denominations: typeof WalletStoresV1.denominations;
|
|
|
|
}>,
|
|
|
|
p: PurchaseRecord,
|
2022-10-15 11:52:07 +02:00
|
|
|
refreshCoinsMap: Record<string, CoinRefreshRequest>,
|
2022-10-08 20:56:57 +02:00
|
|
|
r: MerchantCoinRefundFailureStatus,
|
|
|
|
): Promise<void> {
|
|
|
|
const refundKey = getRefundKey(r);
|
|
|
|
|
|
|
|
const coin = await tx.coins.get(r.coin_pub);
|
|
|
|
if (!coin) {
|
|
|
|
logger.warn("coin not found, can't apply refund");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const denom = await tx.denominations.get([
|
|
|
|
coin.exchangeBaseUrl,
|
|
|
|
coin.denomPubHash,
|
|
|
|
]);
|
|
|
|
|
|
|
|
if (!denom) {
|
|
|
|
throw Error("inconsistent database");
|
|
|
|
}
|
|
|
|
|
|
|
|
const allDenoms = await tx.denominations.indexes.byExchangeBaseUrl
|
|
|
|
.iter(coin.exchangeBaseUrl)
|
|
|
|
.toArray();
|
|
|
|
|
|
|
|
const amountLeft = Amounts.sub(
|
2022-10-15 11:52:07 +02:00
|
|
|
Amounts.parseOrThrow(r.refund_amount),
|
2022-10-08 20:56:57 +02:00
|
|
|
denom.fees.feeRefund,
|
|
|
|
).amount;
|
|
|
|
|
|
|
|
const totalRefreshCostBound = getTotalRefreshCost(
|
|
|
|
allDenoms,
|
|
|
|
DenominationRecord.toDenomInfo(denom),
|
|
|
|
amountLeft,
|
|
|
|
);
|
|
|
|
|
|
|
|
p.refunds[refundKey] = {
|
|
|
|
type: RefundState.Failed,
|
|
|
|
obtainedTime: TalerProtocolTimestamp.now(),
|
|
|
|
executionTime: r.execution_time,
|
2022-11-02 17:42:14 +01:00
|
|
|
refundAmount: Amounts.stringify(r.refund_amount),
|
|
|
|
refundFee: Amounts.stringify(denom.fees.feeRefund),
|
|
|
|
totalRefreshCostBound: Amounts.stringify(totalRefreshCostBound),
|
2022-10-08 20:56:57 +02:00
|
|
|
coinPub: r.coin_pub,
|
|
|
|
rtransactionId: r.rtransaction_id,
|
|
|
|
};
|
|
|
|
|
2022-10-08 23:45:49 +02:00
|
|
|
if (p.purchaseStatus === PurchaseStatus.AbortingWithRefund) {
|
2022-10-08 20:56:57 +02:00
|
|
|
// Refund failed because the merchant didn't even try to deposit
|
|
|
|
// the coin yet, so we try to refresh.
|
2022-10-15 11:52:07 +02:00
|
|
|
// FIXME: Is this case tested?!
|
2022-10-08 20:56:57 +02:00
|
|
|
if (r.exchange_code === TalerErrorCode.EXCHANGE_REFUND_DEPOSIT_NOT_FOUND) {
|
|
|
|
const coin = await tx.coins.get(r.coin_pub);
|
|
|
|
if (!coin) {
|
|
|
|
logger.warn("coin not found, can't apply refund");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const denom = await tx.denominations.get([
|
|
|
|
coin.exchangeBaseUrl,
|
|
|
|
coin.denomPubHash,
|
|
|
|
]);
|
|
|
|
if (!denom) {
|
|
|
|
logger.warn("denomination for coin missing");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const payCoinSelection = p.payInfo?.payCoinSelection;
|
|
|
|
if (!payCoinSelection) {
|
|
|
|
logger.warn("no pay coin selection, can't apply refund");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
let contrib: AmountJson | undefined;
|
|
|
|
for (let i = 0; i < payCoinSelection.coinPubs.length; i++) {
|
|
|
|
if (payCoinSelection.coinPubs[i] === r.coin_pub) {
|
2022-11-02 17:42:14 +01:00
|
|
|
contrib = Amounts.parseOrThrow(payCoinSelection.coinContributions[i]);
|
2022-10-08 20:56:57 +02:00
|
|
|
}
|
|
|
|
}
|
2022-10-15 11:52:07 +02:00
|
|
|
// FIXME: Is this case tested?!
|
|
|
|
refreshCoinsMap[coin.coinPub] = {
|
|
|
|
coinPub: coin.coinPub,
|
2022-11-02 17:42:14 +01:00
|
|
|
amount: Amounts.stringify(amountLeft),
|
2022-10-15 11:52:07 +02:00
|
|
|
};
|
2022-10-08 20:56:57 +02:00
|
|
|
await tx.coins.put(coin);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async function acceptRefunds(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
proposalId: string,
|
|
|
|
refunds: MerchantCoinRefundStatus[],
|
|
|
|
reason: RefundReason,
|
|
|
|
): Promise<void> {
|
|
|
|
logger.trace("handling refunds", refunds);
|
|
|
|
const now = TalerProtocolTimestamp.now();
|
|
|
|
|
|
|
|
await ws.db
|
|
|
|
.mktx((x) => [
|
|
|
|
x.purchases,
|
|
|
|
x.coins,
|
|
|
|
x.coinAvailability,
|
|
|
|
x.denominations,
|
|
|
|
x.refreshGroups,
|
|
|
|
])
|
|
|
|
.runReadWrite(async (tx) => {
|
|
|
|
const p = await tx.purchases.get(proposalId);
|
|
|
|
if (!p) {
|
|
|
|
logger.error("purchase not found, not adding refunds");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-10-15 11:52:07 +02:00
|
|
|
const refreshCoinsMap: Record<string, CoinRefreshRequest> = {};
|
2022-10-08 20:56:57 +02:00
|
|
|
|
|
|
|
for (const refundStatus of refunds) {
|
|
|
|
const refundKey = getRefundKey(refundStatus);
|
|
|
|
const existingRefundInfo = p.refunds[refundKey];
|
|
|
|
|
|
|
|
const isPermanentFailure =
|
|
|
|
refundStatus.type === "failure" &&
|
|
|
|
refundStatus.exchange_status >= 400 &&
|
|
|
|
refundStatus.exchange_status < 500;
|
|
|
|
|
|
|
|
// Already failed.
|
|
|
|
if (existingRefundInfo?.type === RefundState.Failed) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Already applied.
|
|
|
|
if (existingRefundInfo?.type === RefundState.Applied) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Still pending.
|
|
|
|
if (
|
|
|
|
refundStatus.type === "failure" &&
|
|
|
|
!isPermanentFailure &&
|
|
|
|
existingRefundInfo?.type === RefundState.Pending
|
|
|
|
) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Invariant: (!existingRefundInfo) || (existingRefundInfo === Pending)
|
|
|
|
|
|
|
|
if (refundStatus.type === "success") {
|
|
|
|
await applySuccessfulRefund(tx, p, refreshCoinsMap, refundStatus);
|
|
|
|
} else if (isPermanentFailure) {
|
|
|
|
await storeFailedRefund(tx, p, refreshCoinsMap, refundStatus);
|
|
|
|
} else {
|
|
|
|
await storePendingRefund(tx, p, refundStatus);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const refreshCoinsPubs = Object.values(refreshCoinsMap);
|
2022-10-15 11:52:07 +02:00
|
|
|
logger.info(`refreshCoinMap ${j2s(refreshCoinsMap)}`);
|
2022-10-08 20:56:57 +02:00
|
|
|
if (refreshCoinsPubs.length > 0) {
|
|
|
|
await createRefreshGroup(
|
|
|
|
ws,
|
|
|
|
tx,
|
2023-01-05 18:45:49 +01:00
|
|
|
Amounts.currencyOf(refreshCoinsPubs[0].amount),
|
2022-10-08 20:56:57 +02:00
|
|
|
refreshCoinsPubs,
|
|
|
|
RefreshReason.Refund,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Are we done with querying yet, or do we need to do another round
|
|
|
|
// after a retry delay?
|
|
|
|
let queryDone = true;
|
|
|
|
|
|
|
|
let numPendingRefunds = 0;
|
|
|
|
for (const ri of Object.values(p.refunds)) {
|
|
|
|
switch (ri.type) {
|
|
|
|
case RefundState.Pending:
|
|
|
|
numPendingRefunds++;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (numPendingRefunds > 0) {
|
|
|
|
queryDone = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (queryDone) {
|
|
|
|
p.timestampLastRefundStatus = now;
|
2022-10-08 23:45:49 +02:00
|
|
|
if (p.purchaseStatus === PurchaseStatus.AbortingWithRefund) {
|
|
|
|
p.purchaseStatus = PurchaseStatus.PaymentAbortFinished;
|
|
|
|
} else if (p.purchaseStatus === PurchaseStatus.QueryingAutoRefund) {
|
2022-10-08 20:56:57 +02:00
|
|
|
const autoRefundDeadline = p.autoRefundDeadline;
|
|
|
|
checkDbInvariant(!!autoRefundDeadline);
|
|
|
|
if (
|
|
|
|
AbsoluteTime.isExpired(
|
|
|
|
AbsoluteTime.fromTimestamp(autoRefundDeadline),
|
|
|
|
)
|
|
|
|
) {
|
2022-10-08 23:45:49 +02:00
|
|
|
p.purchaseStatus = PurchaseStatus.Paid;
|
2022-10-08 20:56:57 +02:00
|
|
|
}
|
2022-10-08 23:45:49 +02:00
|
|
|
} else if (p.purchaseStatus === PurchaseStatus.QueryingRefund) {
|
|
|
|
p.purchaseStatus = PurchaseStatus.Paid;
|
2022-10-08 20:56:57 +02:00
|
|
|
}
|
|
|
|
logger.trace("refund query done");
|
|
|
|
} else {
|
|
|
|
// No error, but we need to try again!
|
|
|
|
p.timestampLastRefundStatus = now;
|
|
|
|
logger.trace("refund query not done");
|
|
|
|
}
|
|
|
|
|
|
|
|
await tx.purchases.put(p);
|
|
|
|
});
|
|
|
|
|
|
|
|
ws.notify({
|
|
|
|
type: NotificationType.RefundQueried,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async function calculateRefundSummary(
|
2022-10-09 02:23:06 +02:00
|
|
|
ws: InternalWalletState,
|
2022-10-08 20:56:57 +02:00
|
|
|
p: PurchaseRecord,
|
|
|
|
): Promise<RefundSummary> {
|
2022-10-09 02:23:06 +02:00
|
|
|
const download = await expectProposalDownload(ws, p);
|
2022-11-02 17:42:14 +01:00
|
|
|
let amountRefundGranted = Amounts.zeroOfAmount(download.contractData.amount);
|
|
|
|
let amountRefundGone = Amounts.zeroOfAmount(download.contractData.amount);
|
2022-10-08 20:56:57 +02:00
|
|
|
|
|
|
|
let pendingAtExchange = false;
|
|
|
|
|
|
|
|
const payInfo = p.payInfo;
|
|
|
|
if (!payInfo) {
|
|
|
|
throw Error("can't calculate refund summary without payInfo");
|
|
|
|
}
|
|
|
|
|
|
|
|
Object.keys(p.refunds).forEach((rk) => {
|
|
|
|
const refund = p.refunds[rk];
|
|
|
|
if (refund.type === RefundState.Pending) {
|
|
|
|
pendingAtExchange = true;
|
|
|
|
}
|
|
|
|
if (
|
|
|
|
refund.type === RefundState.Applied ||
|
|
|
|
refund.type === RefundState.Pending
|
|
|
|
) {
|
|
|
|
amountRefundGranted = Amounts.add(
|
|
|
|
amountRefundGranted,
|
|
|
|
Amounts.sub(
|
|
|
|
refund.refundAmount,
|
|
|
|
refund.refundFee,
|
|
|
|
refund.totalRefreshCostBound,
|
|
|
|
).amount,
|
|
|
|
).amount;
|
|
|
|
} else {
|
|
|
|
amountRefundGone = Amounts.add(
|
|
|
|
amountRefundGone,
|
|
|
|
refund.refundAmount,
|
|
|
|
).amount;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
return {
|
2022-11-02 17:42:14 +01:00
|
|
|
amountEffectivePaid: Amounts.parseOrThrow(payInfo.totalPayCost),
|
2022-10-08 20:56:57 +02:00
|
|
|
amountRefundGone,
|
|
|
|
amountRefundGranted,
|
|
|
|
pendingAtExchange,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Summary of the refund status of a purchase.
|
|
|
|
*/
|
|
|
|
export interface RefundSummary {
|
|
|
|
pendingAtExchange: boolean;
|
|
|
|
amountEffectivePaid: AmountJson;
|
|
|
|
amountRefundGranted: AmountJson;
|
|
|
|
amountRefundGone: AmountJson;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Accept a refund, return the contract hash for the contract
|
|
|
|
* that was involved in the refund.
|
|
|
|
*/
|
|
|
|
export async function applyRefund(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
talerRefundUri: string,
|
|
|
|
): Promise<ApplyRefundResponse> {
|
|
|
|
const parseResult = parseRefundUri(talerRefundUri);
|
|
|
|
|
|
|
|
logger.trace("applying refund", parseResult);
|
|
|
|
|
|
|
|
if (!parseResult) {
|
|
|
|
throw Error("invalid refund URI");
|
|
|
|
}
|
|
|
|
|
|
|
|
const purchase = await ws.db
|
|
|
|
.mktx((x) => [x.purchases])
|
|
|
|
.runReadOnly(async (tx) => {
|
2022-10-09 02:23:06 +02:00
|
|
|
return tx.purchases.indexes.byUrlAndOrderId.get([
|
2022-10-08 20:56:57 +02:00
|
|
|
parseResult.merchantBaseUrl,
|
|
|
|
parseResult.orderId,
|
|
|
|
]);
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!purchase) {
|
|
|
|
throw Error(
|
|
|
|
`no purchase for the taler://refund/ URI (${talerRefundUri}) was found`,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
return applyRefundFromPurchaseId(ws, purchase.proposalId);
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function applyRefundFromPurchaseId(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
proposalId: string,
|
|
|
|
): Promise<ApplyRefundResponse> {
|
|
|
|
logger.trace("applying refund for purchase", proposalId);
|
|
|
|
|
|
|
|
logger.info("processing purchase for refund");
|
|
|
|
const success = await ws.db
|
|
|
|
.mktx((x) => [x.purchases])
|
|
|
|
.runReadWrite(async (tx) => {
|
|
|
|
const p = await tx.purchases.get(proposalId);
|
|
|
|
if (!p) {
|
|
|
|
logger.error("no purchase found for refund URL");
|
|
|
|
return false;
|
|
|
|
}
|
2022-10-08 23:45:49 +02:00
|
|
|
if (p.purchaseStatus === PurchaseStatus.Paid) {
|
|
|
|
p.purchaseStatus = PurchaseStatus.QueryingRefund;
|
2022-10-08 20:56:57 +02:00
|
|
|
}
|
|
|
|
await tx.purchases.put(p);
|
|
|
|
return true;
|
|
|
|
});
|
|
|
|
|
|
|
|
if (success) {
|
|
|
|
ws.notify({
|
|
|
|
type: NotificationType.RefundStarted,
|
|
|
|
});
|
|
|
|
await processPurchaseQueryRefund(ws, proposalId, {
|
|
|
|
forceNow: true,
|
|
|
|
waitForAutoRefund: false,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
const purchase = await ws.db
|
|
|
|
.mktx((x) => [x.purchases])
|
|
|
|
.runReadOnly(async (tx) => {
|
|
|
|
return tx.purchases.get(proposalId);
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!purchase) {
|
|
|
|
throw Error("purchase no longer exists");
|
|
|
|
}
|
|
|
|
|
2022-10-09 02:23:06 +02:00
|
|
|
const summary = await calculateRefundSummary(ws, purchase);
|
|
|
|
const download = await expectProposalDownload(ws, purchase);
|
2022-10-08 20:56:57 +02:00
|
|
|
|
|
|
|
return {
|
|
|
|
contractTermsHash: download.contractData.contractTermsHash,
|
|
|
|
proposalId: purchase.proposalId,
|
2022-10-14 22:47:11 +02:00
|
|
|
transactionId: makeTransactionId(TransactionType.Payment, proposalId), //FIXME: can we have the tx id of the refund
|
2022-10-08 20:56:57 +02:00
|
|
|
amountEffectivePaid: Amounts.stringify(summary.amountEffectivePaid),
|
|
|
|
amountRefundGone: Amounts.stringify(summary.amountRefundGone),
|
|
|
|
amountRefundGranted: Amounts.stringify(summary.amountRefundGranted),
|
|
|
|
pendingAtExchange: summary.pendingAtExchange,
|
|
|
|
info: {
|
|
|
|
contractTermsHash: download.contractData.contractTermsHash,
|
|
|
|
merchant: download.contractData.merchant,
|
|
|
|
orderId: download.contractData.orderId,
|
|
|
|
products: download.contractData.products,
|
|
|
|
summary: download.contractData.summary,
|
|
|
|
fulfillmentMessage: download.contractData.fulfillmentMessage,
|
|
|
|
summary_i18n: download.contractData.summaryI18n,
|
|
|
|
fulfillmentMessage_i18n: download.contractData.fulfillmentMessageI18n,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
async function queryAndSaveAwaitingRefund(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
purchase: PurchaseRecord,
|
|
|
|
waitForAutoRefund?: boolean,
|
|
|
|
): Promise<AmountJson> {
|
2022-10-09 02:23:06 +02:00
|
|
|
const download = await expectProposalDownload(ws, purchase);
|
2022-10-08 20:56:57 +02:00
|
|
|
const requestUrl = new URL(
|
|
|
|
`orders/${download.contractData.orderId}`,
|
|
|
|
download.contractData.merchantBaseUrl,
|
|
|
|
);
|
|
|
|
requestUrl.searchParams.set(
|
|
|
|
"h_contract",
|
|
|
|
download.contractData.contractTermsHash,
|
|
|
|
);
|
|
|
|
// Long-poll for one second
|
|
|
|
if (waitForAutoRefund) {
|
|
|
|
requestUrl.searchParams.set("timeout_ms", "1000");
|
|
|
|
requestUrl.searchParams.set("await_refund_obtained", "yes");
|
|
|
|
logger.trace("making long-polling request for auto-refund");
|
|
|
|
}
|
|
|
|
const resp = await ws.http.get(requestUrl.href);
|
|
|
|
const orderStatus = await readSuccessResponseJsonOrThrow(
|
|
|
|
resp,
|
|
|
|
codecForMerchantOrderStatusPaid(),
|
|
|
|
);
|
|
|
|
if (!orderStatus.refunded) {
|
|
|
|
// Wait for retry ...
|
2022-11-02 17:42:14 +01:00
|
|
|
return Amounts.zeroOfAmount(download.contractData.amount);
|
2022-10-08 20:56:57 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
const refundAwaiting = Amounts.sub(
|
|
|
|
Amounts.parseOrThrow(orderStatus.refund_amount),
|
|
|
|
Amounts.parseOrThrow(orderStatus.refund_taken),
|
|
|
|
).amount;
|
|
|
|
|
|
|
|
if (
|
|
|
|
purchase.refundAmountAwaiting === undefined ||
|
|
|
|
Amounts.cmp(refundAwaiting, purchase.refundAmountAwaiting) !== 0
|
|
|
|
) {
|
|
|
|
await ws.db
|
|
|
|
.mktx((x) => [x.purchases])
|
|
|
|
.runReadWrite(async (tx) => {
|
|
|
|
const p = await tx.purchases.get(purchase.proposalId);
|
|
|
|
if (!p) {
|
|
|
|
logger.warn("purchase does not exist anymore");
|
|
|
|
return;
|
|
|
|
}
|
2022-11-02 17:42:14 +01:00
|
|
|
p.refundAmountAwaiting = Amounts.stringify(refundAwaiting);
|
2022-10-08 20:56:57 +02:00
|
|
|
await tx.purchases.put(p);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return refundAwaiting;
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function processPurchaseQueryRefund(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
proposalId: string,
|
|
|
|
options: {
|
|
|
|
forceNow?: boolean;
|
|
|
|
waitForAutoRefund?: boolean;
|
|
|
|
} = {},
|
|
|
|
): Promise<OperationAttemptResult> {
|
|
|
|
logger.trace(`processing refund query for proposal ${proposalId}`);
|
|
|
|
const waitForAutoRefund = options.waitForAutoRefund ?? false;
|
|
|
|
const purchase = await ws.db
|
|
|
|
.mktx((x) => [x.purchases])
|
|
|
|
.runReadOnly(async (tx) => {
|
|
|
|
return tx.purchases.get(proposalId);
|
|
|
|
});
|
|
|
|
if (!purchase) {
|
|
|
|
return OperationAttemptResult.finishedEmpty();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (
|
|
|
|
!(
|
2022-10-08 23:45:49 +02:00
|
|
|
purchase.purchaseStatus === PurchaseStatus.QueryingAutoRefund ||
|
|
|
|
purchase.purchaseStatus === PurchaseStatus.QueryingRefund ||
|
|
|
|
purchase.purchaseStatus === PurchaseStatus.AbortingWithRefund
|
2022-10-08 20:56:57 +02:00
|
|
|
)
|
|
|
|
) {
|
|
|
|
return OperationAttemptResult.finishedEmpty();
|
|
|
|
}
|
|
|
|
|
2022-10-09 02:23:06 +02:00
|
|
|
const download = await expectProposalDownload(ws, purchase);
|
2022-10-08 20:56:57 +02:00
|
|
|
|
|
|
|
if (purchase.timestampFirstSuccessfulPay) {
|
|
|
|
if (
|
|
|
|
!purchase.autoRefundDeadline ||
|
|
|
|
!AbsoluteTime.isExpired(
|
|
|
|
AbsoluteTime.fromTimestamp(purchase.autoRefundDeadline),
|
|
|
|
)
|
|
|
|
) {
|
|
|
|
const awaitingAmount = await queryAndSaveAwaitingRefund(
|
|
|
|
ws,
|
|
|
|
purchase,
|
|
|
|
waitForAutoRefund,
|
|
|
|
);
|
|
|
|
if (Amounts.isZero(awaitingAmount)) {
|
|
|
|
return OperationAttemptResult.finishedEmpty();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const requestUrl = new URL(
|
|
|
|
`orders/${download.contractData.orderId}/refund`,
|
|
|
|
download.contractData.merchantBaseUrl,
|
|
|
|
);
|
|
|
|
|
|
|
|
logger.trace(`making refund request to ${requestUrl.href}`);
|
|
|
|
|
|
|
|
const request = await ws.http.postJson(requestUrl.href, {
|
|
|
|
h_contract: download.contractData.contractTermsHash,
|
|
|
|
});
|
|
|
|
|
|
|
|
const refundResponse = await readSuccessResponseJsonOrThrow(
|
|
|
|
request,
|
|
|
|
codecForMerchantOrderRefundPickupResponse(),
|
|
|
|
);
|
|
|
|
|
|
|
|
await acceptRefunds(
|
|
|
|
ws,
|
|
|
|
proposalId,
|
|
|
|
refundResponse.refunds,
|
|
|
|
RefundReason.NormalRefund,
|
|
|
|
);
|
2022-10-08 23:45:49 +02:00
|
|
|
} else if (purchase.purchaseStatus === PurchaseStatus.AbortingWithRefund) {
|
2022-10-08 20:56:57 +02:00
|
|
|
const requestUrl = new URL(
|
|
|
|
`orders/${download.contractData.orderId}/abort`,
|
|
|
|
download.contractData.merchantBaseUrl,
|
|
|
|
);
|
|
|
|
|
|
|
|
const abortingCoins: AbortingCoin[] = [];
|
|
|
|
|
|
|
|
const payCoinSelection = purchase.payInfo?.payCoinSelection;
|
|
|
|
if (!payCoinSelection) {
|
|
|
|
throw Error("can't abort, no coins selected");
|
|
|
|
}
|
|
|
|
|
|
|
|
await ws.db
|
|
|
|
.mktx((x) => [x.coins])
|
|
|
|
.runReadOnly(async (tx) => {
|
|
|
|
for (let i = 0; i < payCoinSelection.coinPubs.length; i++) {
|
|
|
|
const coinPub = payCoinSelection.coinPubs[i];
|
|
|
|
const coin = await tx.coins.get(coinPub);
|
|
|
|
checkDbInvariant(!!coin, "expected coin to be present");
|
|
|
|
abortingCoins.push({
|
|
|
|
coin_pub: coinPub,
|
|
|
|
contribution: Amounts.stringify(
|
|
|
|
payCoinSelection.coinContributions[i],
|
|
|
|
),
|
|
|
|
exchange_url: coin.exchangeBaseUrl,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
const abortReq: AbortRequest = {
|
|
|
|
h_contract: download.contractData.contractTermsHash,
|
|
|
|
coins: abortingCoins,
|
|
|
|
};
|
|
|
|
|
|
|
|
logger.trace(`making order abort request to ${requestUrl.href}`);
|
|
|
|
|
|
|
|
const request = await ws.http.postJson(requestUrl.href, abortReq);
|
|
|
|
const abortResp = await readSuccessResponseJsonOrThrow(
|
|
|
|
request,
|
|
|
|
codecForAbortResponse(),
|
|
|
|
);
|
|
|
|
|
|
|
|
const refunds: MerchantCoinRefundStatus[] = [];
|
|
|
|
|
|
|
|
if (abortResp.refunds.length != abortingCoins.length) {
|
|
|
|
// FIXME: define error code!
|
|
|
|
throw Error("invalid order abort response");
|
|
|
|
}
|
|
|
|
|
|
|
|
for (let i = 0; i < abortResp.refunds.length; i++) {
|
|
|
|
const r = abortResp.refunds[i];
|
|
|
|
refunds.push({
|
|
|
|
...r,
|
|
|
|
coin_pub: payCoinSelection.coinPubs[i],
|
|
|
|
refund_amount: Amounts.stringify(payCoinSelection.coinContributions[i]),
|
|
|
|
rtransaction_id: 0,
|
|
|
|
execution_time: AbsoluteTime.toTimestamp(
|
|
|
|
AbsoluteTime.addDuration(
|
|
|
|
AbsoluteTime.fromTimestamp(download.contractData.timestamp),
|
|
|
|
Duration.fromSpec({ seconds: 1 }),
|
|
|
|
),
|
|
|
|
),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
await acceptRefunds(ws, proposalId, refunds, RefundReason.AbortRefund);
|
|
|
|
}
|
|
|
|
return OperationAttemptResult.finishedEmpty();
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function abortFailedPayWithRefund(
|
|
|
|
ws: InternalWalletState,
|
|
|
|
proposalId: string,
|
|
|
|
): Promise<void> {
|
|
|
|
await ws.db
|
|
|
|
.mktx((x) => [x.purchases])
|
|
|
|
.runReadWrite(async (tx) => {
|
|
|
|
const purchase = await tx.purchases.get(proposalId);
|
|
|
|
if (!purchase) {
|
|
|
|
throw Error("purchase not found");
|
|
|
|
}
|
|
|
|
if (purchase.timestampFirstSuccessfulPay) {
|
|
|
|
// No point in aborting it. We don't even report an error.
|
|
|
|
logger.warn(`tried to abort successful payment`);
|
|
|
|
return;
|
|
|
|
}
|
2022-10-08 23:45:49 +02:00
|
|
|
if (purchase.purchaseStatus === PurchaseStatus.Paying) {
|
|
|
|
purchase.purchaseStatus = PurchaseStatus.AbortingWithRefund;
|
2022-10-08 20:56:57 +02:00
|
|
|
}
|
|
|
|
await tx.purchases.put(purchase);
|
|
|
|
});
|
|
|
|
processPurchaseQueryRefund(ws, proposalId, {
|
|
|
|
forceNow: true,
|
|
|
|
}).catch((e) => {
|
|
|
|
logger.trace(`error during refund processing after abort pay: ${e}`);
|
|
|
|
});
|
|
|
|
}
|