wallet-core/packages/taler-wallet-core/src/operations/transactions.ts

612 lines
19 KiB
TypeScript
Raw Normal View History

2020-05-12 10:38:58 +02:00
/*
This file is part of GNU Taler
(C) 2019 Taler Systems S.A.
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/>
*/
/**
* Imports.
*/
import {
2022-03-18 15:32:41 +01:00
AbsoluteTime,
AmountJson,
Amounts,
Logger,
OrderShortInfo,
PaymentStatus,
Transaction,
TransactionsRequest,
TransactionsResponse,
TransactionType,
WithdrawalDetails,
WithdrawalType,
} from "@gnu-taler/taler-util";
import { InternalWalletState } from "../internal-wallet-state.js";
import {
AbortStatus,
RefundState,
ReserveRecord,
ReserveRecordStatus,
WalletRefundItem,
2021-03-17 17:56:37 +01:00
} from "../db.js";
import { processDepositGroup } from "./deposits.js";
import { getExchangeDetails } from "./exchanges.js";
2021-06-14 19:37:35 +02:00
import { processPurchasePay } from "./pay.js";
import { processRefreshGroup } from "./refresh.js";
import { getFundingPaytoUris } from "./reserves.js";
import { processTip } from "./tip.js";
import { processWithdrawGroup } from "./withdraw.js";
2020-05-12 10:38:58 +02:00
const logger = new Logger("taler-wallet-core:transactions.ts");
2020-05-12 10:38:58 +02:00
/**
* Create an event ID from the type and the primary key for the event.
*/
2021-05-21 11:47:11 +02:00
export function makeEventId(
type: TransactionType | TombstoneTag,
...args: string[]
): string {
return type + ":" + args.map((x) => encodeURIComponent(x)).join(":");
2020-05-12 10:38:58 +02:00
}
2020-05-15 13:28:15 +02:00
function shouldSkipCurrency(
transactionsRequest: TransactionsRequest | undefined,
currency: string,
): boolean {
if (!transactionsRequest?.currency) {
return false;
}
return transactionsRequest.currency.toLowerCase() !== currency.toLowerCase();
}
function shouldSkipSearch(
transactionsRequest: TransactionsRequest | undefined,
fields: string[],
): boolean {
if (!transactionsRequest?.search) {
return false;
}
const needle = transactionsRequest.search.trim();
for (const f of fields) {
if (f.indexOf(needle) >= 0) {
return false;
}
}
return true;
}
2020-05-12 10:38:58 +02:00
/**
2021-04-27 23:42:25 +02:00
* Retrieve the full event history for this wallet.
2020-05-12 10:38:58 +02:00
*/
export async function getTransactions(
ws: InternalWalletState,
transactionsRequest?: TransactionsRequest,
): Promise<TransactionsResponse> {
const transactions: Transaction[] = [];
2021-06-09 15:14:17 +02:00
await ws.db
.mktx((x) => ({
coins: x.coins,
denominations: x.denominations,
exchanges: x.exchanges,
exchangeDetails: x.exchangeDetails,
proposals: x.proposals,
purchases: x.purchases,
refreshGroups: x.refreshGroups,
reserves: x.reserves,
tips: x.tips,
withdrawalGroups: x.withdrawalGroups,
planchets: x.planchets,
recoupGroups: x.recoupGroups,
depositGroups: x.depositGroups,
tombstones: x.tombstones,
}))
.runReadOnly(
// Report withdrawals that are currently in progress.
async (tx) => {
tx.withdrawalGroups.iter().forEachAsync(async (wsr) => {
if (
shouldSkipCurrency(
transactionsRequest,
wsr.rawWithdrawalAmount.currency,
)
) {
return;
}
2020-05-15 13:28:15 +02:00
2021-06-09 15:14:17 +02:00
if (shouldSkipSearch(transactionsRequest, [])) {
return;
}
2020-05-15 13:28:15 +02:00
2021-06-09 15:14:17 +02:00
const r = await tx.reserves.get(wsr.reservePub);
if (!r) {
2020-09-08 15:57:08 +02:00
return;
}
2021-06-09 15:14:17 +02:00
let amountRaw: AmountJson | undefined = undefined;
if (wsr.withdrawalGroupId === r.initialWithdrawalGroupId) {
amountRaw = r.instructedAmount;
} else {
amountRaw = wsr.denomsSel.totalWithdrawCost;
}
let withdrawalDetails: WithdrawalDetails;
if (r.bankInfo) {
withdrawalDetails = {
type: WithdrawalType.TalerBankIntegrationApi,
confirmed: true,
reservePub: wsr.reservePub,
2021-06-09 15:14:17 +02:00
bankConfirmationUrl: r.bankInfo.confirmUrl,
};
} else {
const exchangeDetails = await getExchangeDetails(
tx,
wsr.exchangeBaseUrl,
);
if (!exchangeDetails) {
// FIXME: report somehow
return;
}
withdrawalDetails = {
type: WithdrawalType.ManualTransfer,
reservePub: wsr.reservePub,
2021-06-09 15:14:17 +02:00
exchangePaytoUris:
exchangeDetails.wireInfo?.accounts.map((x) => x.payto_uri) ??
[],
};
}
2021-06-09 15:14:17 +02:00
transactions.push({
type: TransactionType.Withdrawal,
amountEffective: Amounts.stringify(wsr.denomsSel.totalCoinValue),
amountRaw: Amounts.stringify(amountRaw),
withdrawalDetails,
exchangeBaseUrl: wsr.exchangeBaseUrl,
pending: !wsr.timestampFinish,
timestamp: wsr.timestampStart,
transactionId: makeEventId(
TransactionType.Withdrawal,
wsr.withdrawalGroupId,
),
2021-08-24 15:08:34 +02:00
frozen: false,
2021-06-09 15:14:17 +02:00
...(wsr.lastError ? { error: wsr.lastError } : {}),
});
2020-09-08 15:57:08 +02:00
});
2020-05-12 10:38:58 +02:00
2021-06-09 15:14:17 +02:00
// Report pending withdrawals based on reserves that
// were created, but where the actual withdrawal group has
// not started yet.
tx.reserves.iter().forEachAsync(async (r) => {
if (shouldSkipCurrency(transactionsRequest, r.currency)) {
return;
}
if (shouldSkipSearch(transactionsRequest, [])) {
return;
}
if (r.initialWithdrawalStarted) {
return;
}
if (r.reserveStatus === ReserveRecordStatus.BankAborted) {
2021-06-09 15:14:17 +02:00
return;
}
let withdrawalDetails: WithdrawalDetails;
if (r.bankInfo) {
withdrawalDetails = {
type: WithdrawalType.TalerBankIntegrationApi,
confirmed: false,
reservePub: r.reservePub,
2021-06-09 15:14:17 +02:00
bankConfirmationUrl: r.bankInfo.confirmUrl,
};
} else {
withdrawalDetails = {
type: WithdrawalType.ManualTransfer,
reservePub: r.reservePub,
2021-06-09 15:14:17 +02:00
exchangePaytoUris: await getFundingPaytoUris(tx, r.reservePub),
};
}
transactions.push({
type: TransactionType.Withdrawal,
amountRaw: Amounts.stringify(r.instructedAmount),
amountEffective: Amounts.stringify(
r.initialDenomSel.totalCoinValue,
),
exchangeBaseUrl: r.exchangeBaseUrl,
pending: true,
timestamp: r.timestampCreated,
withdrawalDetails: withdrawalDetails,
transactionId: makeEventId(
TransactionType.Withdrawal,
r.initialWithdrawalGroupId,
),
2021-08-24 15:08:34 +02:00
frozen: false,
2021-06-09 15:14:17 +02:00
...(r.lastError ? { error: r.lastError } : {}),
});
2020-05-12 10:38:58 +02:00
});
2021-06-09 15:14:17 +02:00
tx.depositGroups.iter().forEachAsync(async (dg) => {
const amount = Amounts.parseOrThrow(dg.contractTermsRaw.amount);
if (shouldSkipCurrency(transactionsRequest, amount.currency)) {
return;
}
2021-01-18 23:35:41 +01:00
2021-06-09 15:14:17 +02:00
transactions.push({
type: TransactionType.Deposit,
amountRaw: Amounts.stringify(dg.effectiveDepositAmount),
amountEffective: Amounts.stringify(dg.totalPayCost),
pending: !dg.timestampFinished,
2021-08-24 15:08:34 +02:00
frozen: false,
2021-06-09 15:14:17 +02:00
timestamp: dg.timestampCreated,
targetPaytoUri: dg.wire.payto_uri,
transactionId: makeEventId(
TransactionType.Deposit,
dg.depositGroupId,
),
depositGroupId: dg.depositGroupId,
...(dg.lastError ? { error: dg.lastError } : {}),
});
});
2021-06-09 15:14:17 +02:00
tx.purchases.iter().forEachAsync(async (pr) => {
if (
shouldSkipCurrency(
transactionsRequest,
pr.download.contractData.amount.currency,
)
) {
return;
}
2021-06-09 15:14:17 +02:00
const contractData = pr.download.contractData;
if (shouldSkipSearch(transactionsRequest, [contractData.summary])) {
return;
}
const proposal = await tx.proposals.get(pr.proposalId);
if (!proposal) {
return;
}
const info: OrderShortInfo = {
merchant: contractData.merchant,
orderId: contractData.orderId,
products: contractData.products,
summary: contractData.summary,
summary_i18n: contractData.summaryI18n,
contractTermsHash: contractData.contractTermsHash,
};
if (contractData.fulfillmentUrl !== "") {
info.fulfillmentUrl = contractData.fulfillmentUrl;
}
const paymentTransactionId = makeEventId(
TransactionType.Payment,
pr.proposalId,
);
2021-06-09 15:14:17 +02:00
const err = pr.lastPayError ?? pr.lastRefundStatusError;
transactions.push({
type: TransactionType.Payment,
amountRaw: Amounts.stringify(contractData.amount),
amountEffective: Amounts.stringify(pr.totalPayCost),
status: pr.timestampFirstSuccessfulPay
? PaymentStatus.Paid
: PaymentStatus.Accepted,
pending:
!pr.timestampFirstSuccessfulPay &&
pr.abortStatus === AbortStatus.None,
timestamp: pr.timestampAccept,
transactionId: paymentTransactionId,
proposalId: pr.proposalId,
info: info,
2021-08-24 15:08:34 +02:00
frozen: pr.payFrozen ?? false,
2021-06-09 15:14:17 +02:00
...(err ? { error: err } : {}),
});
const refundGroupKeys = new Set<string>();
for (const rk of Object.keys(pr.refunds)) {
const refund = pr.refunds[rk];
2022-03-18 15:32:41 +01:00
const groupKey = `${refund.executionTime.t_s}`;
2021-06-09 15:14:17 +02:00
refundGroupKeys.add(groupKey);
}
for (const groupKey of refundGroupKeys.values()) {
const refundTombstoneId = makeEventId(
TombstoneTag.DeleteRefund,
pr.proposalId,
groupKey,
);
const tombstone = await tx.tombstones.get(refundTombstoneId);
if (tombstone) {
continue;
}
2021-06-09 15:14:17 +02:00
const refundTransactionId = makeEventId(
TransactionType.Refund,
pr.proposalId,
groupKey,
);
let r0: WalletRefundItem | undefined;
let amountRaw = Amounts.getZero(contractData.amount.currency);
let amountEffective = Amounts.getZero(contractData.amount.currency);
for (const rk of Object.keys(pr.refunds)) {
const refund = pr.refunds[rk];
2022-03-18 15:32:41 +01:00
const myGroupKey = `${refund.executionTime.t_s}`;
2021-06-09 15:14:17 +02:00
if (myGroupKey !== groupKey) {
continue;
}
if (!r0) {
r0 = refund;
}
if (refund.type === RefundState.Applied) {
amountRaw = Amounts.add(amountRaw, refund.refundAmount).amount;
amountEffective = Amounts.add(
amountEffective,
Amounts.sub(
refund.refundAmount,
refund.refundFee,
refund.totalRefreshCostBound,
).amount,
).amount;
}
}
if (!r0) {
2021-06-09 15:14:17 +02:00
throw Error("invariant violated");
}
2021-06-09 15:14:17 +02:00
transactions.push({
type: TransactionType.Refund,
info,
refundedTransactionId: paymentTransactionId,
transactionId: refundTransactionId,
timestamp: r0.obtainedTime,
amountEffective: Amounts.stringify(amountEffective),
amountRaw: Amounts.stringify(amountRaw),
pending: false,
2021-08-24 15:08:34 +02:00
frozen: false,
2021-06-09 15:14:17 +02:00
});
}
});
2021-06-09 15:14:17 +02:00
tx.tips.iter().forEachAsync(async (tipRecord) => {
if (
shouldSkipCurrency(
transactionsRequest,
tipRecord.tipAmountRaw.currency,
)
) {
return;
}
2021-06-09 15:14:17 +02:00
if (!tipRecord.acceptedTimestamp) {
return;
}
transactions.push({
2021-06-09 15:14:17 +02:00
type: TransactionType.Tip,
amountEffective: Amounts.stringify(tipRecord.tipAmountEffective),
amountRaw: Amounts.stringify(tipRecord.tipAmountRaw),
pending: !tipRecord.pickedUpTimestamp,
2021-08-24 15:08:34 +02:00
frozen: false,
2021-06-09 15:14:17 +02:00
timestamp: tipRecord.acceptedTimestamp,
transactionId: makeEventId(
TransactionType.Tip,
tipRecord.walletTipId,
),
merchantBaseUrl: tipRecord.merchantBaseUrl,
error: tipRecord.lastError,
});
});
2021-06-09 15:14:17 +02:00
},
);
2020-05-12 10:38:58 +02:00
2020-05-15 20:22:58 +02:00
const txPending = transactions.filter((x) => x.pending);
const txNotPending = transactions.filter((x) => !x.pending);
2022-03-18 15:32:41 +01:00
txPending.sort((h1, h2) =>
AbsoluteTime.cmp(
AbsoluteTime.fromTimestamp(h1.timestamp),
AbsoluteTime.fromTimestamp(h2.timestamp),
),
);
txNotPending.sort((h1, h2) =>
AbsoluteTime.cmp(
AbsoluteTime.fromTimestamp(h1.timestamp),
AbsoluteTime.fromTimestamp(h2.timestamp),
),
);
2020-05-12 10:38:58 +02:00
return { transactions: [...txNotPending, ...txPending] };
2020-05-12 10:38:58 +02:00
}
export enum TombstoneTag {
2021-05-20 17:11:44 +02:00
DeleteWithdrawalGroup = "delete-withdrawal-group",
DeleteReserve = "delete-reserve",
DeletePayment = "delete-payment",
DeleteTip = "delete-tip",
DeleteRefreshGroup = "delete-refresh-group",
DeleteDepositGroup = "delete-deposit-group",
DeleteRefund = "delete-refund",
}
2021-06-14 19:37:35 +02:00
/**
* Immediately retry the underlying operation
* of a transaction.
*/
export async function retryTransaction(
ws: InternalWalletState,
transactionId: string,
): Promise<void> {
logger.info(`retrying transaction ${transactionId}`);
2021-06-14 19:37:35 +02:00
const [type, ...rest] = transactionId.split(":");
switch (type) {
case TransactionType.Deposit:
const depositGroupId = rest[0];
processDepositGroup(ws, depositGroupId, true);
break;
case TransactionType.Withdrawal:
2021-06-14 19:37:35 +02:00
const withdrawalGroupId = rest[0];
await processWithdrawGroup(ws, withdrawalGroupId, true);
break;
case TransactionType.Payment:
const proposalId = rest[0];
2021-06-14 19:37:35 +02:00
await processPurchasePay(ws, proposalId, true);
break;
case TransactionType.Tip:
2021-06-14 19:37:35 +02:00
const walletTipId = rest[0];
await processTip(ws, walletTipId, true);
break;
case TransactionType.Refresh:
2021-06-14 19:37:35 +02:00
const refreshGroupId = rest[0];
await processRefreshGroup(ws, refreshGroupId, true);
break;
default:
break;
}
}
/**
2021-05-21 13:32:49 +02:00
* Permanently delete a transaction based on the transaction ID.
*/
export async function deleteTransaction(
ws: InternalWalletState,
transactionId: string,
): Promise<void> {
const [type, ...rest] = transactionId.split(":");
if (type === TransactionType.Withdrawal) {
const withdrawalGroupId = rest[0];
2021-06-09 15:14:17 +02:00
await ws.db
.mktx((x) => ({
withdrawalGroups: x.withdrawalGroups,
reserves: x.reserves,
tombstones: x.tombstones,
}))
.runReadWrite(async (tx) => {
const withdrawalGroupRecord = await tx.withdrawalGroups.get(
withdrawalGroupId,
);
if (withdrawalGroupRecord) {
2021-06-09 15:14:17 +02:00
await tx.withdrawalGroups.delete(withdrawalGroupId);
await tx.tombstones.put({
2021-05-20 17:11:44 +02:00
id: TombstoneTag.DeleteWithdrawalGroup + ":" + withdrawalGroupId,
});
return;
}
2022-03-18 15:32:41 +01:00
const reserveRecord: ReserveRecord | undefined =
await tx.reserves.indexes.byInitialWithdrawalGroupId.get(
withdrawalGroupId,
);
if (reserveRecord && !reserveRecord.initialWithdrawalStarted) {
const reservePub = reserveRecord.reservePub;
2021-06-09 15:14:17 +02:00
await tx.reserves.delete(reservePub);
await tx.tombstones.put({
2021-05-20 17:11:44 +02:00
id: TombstoneTag.DeleteReserve + ":" + reservePub,
});
}
2021-06-09 15:14:17 +02:00
});
2021-05-20 17:11:44 +02:00
} else if (type === TransactionType.Payment) {
const proposalId = rest[0];
2021-06-09 15:14:17 +02:00
await ws.db
.mktx((x) => ({
proposals: x.proposals,
purchases: x.purchases,
tombstones: x.tombstones,
}))
.runReadWrite(async (tx) => {
2021-05-20 17:11:44 +02:00
let found = false;
2021-06-09 15:14:17 +02:00
const proposal = await tx.proposals.get(proposalId);
2021-05-20 17:11:44 +02:00
if (proposal) {
found = true;
2021-06-09 15:14:17 +02:00
await tx.proposals.delete(proposalId);
2021-05-20 17:11:44 +02:00
}
2021-06-09 15:14:17 +02:00
const purchase = await tx.purchases.get(proposalId);
2021-05-20 17:11:44 +02:00
if (purchase) {
found = true;
await tx.purchases.delete(proposalId);
2021-05-20 17:11:44 +02:00
}
if (found) {
2021-06-09 15:14:17 +02:00
await tx.tombstones.put({
2021-05-20 17:11:44 +02:00
id: TombstoneTag.DeletePayment + ":" + proposalId,
});
}
2021-06-09 15:14:17 +02:00
});
2021-05-20 17:11:44 +02:00
} else if (type === TransactionType.Refresh) {
const refreshGroupId = rest[0];
2021-06-09 15:14:17 +02:00
await ws.db
.mktx((x) => ({
refreshGroups: x.refreshGroups,
tombstones: x.tombstones,
}))
.runReadWrite(async (tx) => {
const rg = await tx.refreshGroups.get(refreshGroupId);
2021-05-20 17:11:44 +02:00
if (rg) {
2021-06-09 15:14:17 +02:00
await tx.refreshGroups.delete(refreshGroupId);
await tx.tombstones.put({
2021-05-20 17:11:44 +02:00
id: TombstoneTag.DeleteRefreshGroup + ":" + refreshGroupId,
});
}
2021-06-09 15:14:17 +02:00
});
2021-05-20 17:11:44 +02:00
} else if (type === TransactionType.Tip) {
const tipId = rest[0];
2021-06-09 15:14:17 +02:00
await ws.db
.mktx((x) => ({
tips: x.tips,
tombstones: x.tombstones,
}))
.runReadWrite(async (tx) => {
const tipRecord = await tx.tips.get(tipId);
2021-05-20 17:11:44 +02:00
if (tipRecord) {
2021-06-09 15:14:17 +02:00
await tx.tips.delete(tipId);
await tx.tombstones.put({
2021-05-20 17:11:44 +02:00
id: TombstoneTag.DeleteTip + ":" + tipId,
});
}
2021-06-09 15:14:17 +02:00
});
2021-05-20 17:11:44 +02:00
} else if (type === TransactionType.Deposit) {
const depositGroupId = rest[0];
2021-06-09 15:14:17 +02:00
await ws.db
.mktx((x) => ({
depositGroups: x.depositGroups,
tombstones: x.tombstones,
}))
.runReadWrite(async (tx) => {
const tipRecord = await tx.depositGroups.get(depositGroupId);
2021-05-20 17:11:44 +02:00
if (tipRecord) {
2021-06-09 15:14:17 +02:00
await tx.depositGroups.delete(depositGroupId);
await tx.tombstones.put({
2021-05-20 17:11:44 +02:00
id: TombstoneTag.DeleteDepositGroup + ":" + depositGroupId,
});
}
2021-06-09 15:14:17 +02:00
});
} else if (type === TransactionType.Refund) {
const proposalId = rest[0];
const executionTimeStr = rest[1];
2021-06-09 15:14:17 +02:00
await ws.db
.mktx((x) => ({
proposals: x.proposals,
purchases: x.purchases,
tombstones: x.tombstones,
}))
.runReadWrite(async (tx) => {
const purchase = await tx.purchases.get(proposalId);
if (purchase) {
// This should just influence the history view,
// but won't delete any actual refund information.
2021-06-09 15:14:17 +02:00
await tx.tombstones.put({
id: makeEventId(
TombstoneTag.DeleteRefund,
proposalId,
executionTimeStr,
),
});
}
2021-06-09 15:14:17 +02:00
});
} else {
throw Error(`can't delete a '${type}' transaction`);
}
}