aboutsummaryrefslogtreecommitdiff
path: root/packages/taler-wallet-core/src/transactions.ts
blob: b77393f6e12855f7c9105a5374e40f34990b7371 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
/*
 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 {
  BridgeIDBKeyRange,
  GlobalIDB,
  IDBKeyRange,
} from "@gnu-taler/idb-bridge";
import {
  AbsoluteTime,
  Amounts,
  assertUnreachable,
  GetTransactionsV2Request,
  j2s,
  Logger,
  makeTalerErrorDetail,
  NotificationType,
  ScopeType,
  TalerErrorCode,
  Transaction,
  TransactionByIdRequest,
  TransactionIdStr,
  TransactionMajorState,
  TransactionsRequest,
  TransactionsResponse,
  TransactionState,
  TransactionType,
} from "@gnu-taler/taler-util";
import {
  constructTaskIdentifier,
  PendingTaskType,
  TaskIdStr,
  TransactionContext,
} from "./common.js";
import {
  DbPreciseTimestamp,
  OPERATION_STATUS_DONE_FIRST,
  OPERATION_STATUS_DONE_LAST,
  OPERATION_STATUS_NONFINAL_FIRST,
  OPERATION_STATUS_NONFINAL_LAST,
  timestampPreciseToDb,
  TransactionMetaRecord,
  WalletDbAllStoresReadOnlyTransaction,
  WalletDbAllStoresReadWriteTransaction,
} from "./db.js";
import { DepositTransactionContext } from "./deposits.js";
import { DenomLossTransactionContext } from "./exchanges.js";
import {
  PayMerchantTransactionContext,
  RefundTransactionContext,
} from "./pay-merchant.js";
import { PeerPullCreditTransactionContext } from "./pay-peer-pull-credit.js";
import { PeerPullDebitTransactionContext } from "./pay-peer-pull-debit.js";
import { PeerPushCreditTransactionContext } from "./pay-peer-push-credit.js";
import { PeerPushDebitTransactionContext } from "./pay-peer-push-debit.js";
import { RefreshTransactionContext } from "./refresh.js";
import type { WalletExecutionContext } from "./wallet.js";
import { WithdrawTransactionContext } from "./withdraw.js";

const logger = new Logger("taler-wallet-core:transactions.ts");

function shouldSkipCurrency(
  transactionsRequest:
    | TransactionsRequest
    | GetTransactionsV2Request
    | undefined,
  currency: string,
  exchangesInTransaction: string[],
): boolean {
  if (transactionsRequest?.scopeInfo) {
    const sameCurrency = Amounts.isSameCurrency(
      currency,
      transactionsRequest.scopeInfo.currency,
    );
    switch (transactionsRequest.scopeInfo.type) {
      case ScopeType.Global: {
        return !sameCurrency;
      }
      case ScopeType.Exchange: {
        return (
          !sameCurrency ||
          (exchangesInTransaction.length > 0 &&
            !exchangesInTransaction.includes(transactionsRequest.scopeInfo.url))
        );
      }
      case ScopeType.Auditor: {
        // same currency and same auditor
        throw Error("filering balance in auditor scope is not implemented");
      }
      default:
        assertUnreachable(transactionsRequest.scopeInfo);
    }
  }
  if (transactionsRequest?.currency) {
    return (
      transactionsRequest.currency.toLowerCase() !== currency.toLowerCase()
    );
  }
  return false;
}

/**
 * Fallback order of transactions that have the same timestamp.
 */
const txOrder: { [t in TransactionType]: number } = {
  [TransactionType.Withdrawal]: 1,
  [TransactionType.Payment]: 3,
  [TransactionType.PeerPullCredit]: 4,
  [TransactionType.PeerPullDebit]: 5,
  [TransactionType.PeerPushCredit]: 6,
  [TransactionType.PeerPushDebit]: 7,
  [TransactionType.Refund]: 8,
  [TransactionType.Deposit]: 9,
  [TransactionType.Refresh]: 10,
  [TransactionType.Recoup]: 11,
  [TransactionType.InternalWithdrawal]: 12,
  [TransactionType.DenomLoss]: 13,
};

export async function getTransactionById(
  wex: WalletExecutionContext,
  req: TransactionByIdRequest,
): Promise<Transaction> {
  const parsedTx = parseTransactionIdentifier(req.transactionId);

  if (!parsedTx) {
    throw Error("invalid transaction ID");
  }

  switch (parsedTx.tag) {
    case TransactionType.InternalWithdrawal:
    case TransactionType.Withdrawal:
    case TransactionType.DenomLoss:
    case TransactionType.Recoup:
    case TransactionType.PeerPushDebit:
    case TransactionType.PeerPushCredit:
    case TransactionType.Refresh:
    case TransactionType.PeerPullCredit:
    case TransactionType.Payment:
    case TransactionType.Deposit:
    case TransactionType.PeerPullDebit:
    case TransactionType.Refund: {
      const ctx = await getContextForTransaction(wex, req.transactionId);
      const txDetails = await wex.db.runAllStoresReadOnlyTx({}, async (tx) =>
        ctx.lookupFullTransaction(tx),
      );
      if (!txDetails) {
        throw Error("transaction not found");
      }
      return txDetails;
    }
  }
}

export function isUnsuccessfulTransaction(state: TransactionState): boolean {
  return (
    state.major === TransactionMajorState.Aborted ||
    state.major === TransactionMajorState.Expired ||
    state.major === TransactionMajorState.Aborting ||
    state.major === TransactionMajorState.Deleted ||
    state.major === TransactionMajorState.Failed
  );
}

function checkFilterIncludes(
  req: GetTransactionsV2Request | undefined,
  mtx: TransactionMetaRecord,
): boolean {
  if (shouldSkipCurrency(req, mtx.currency, mtx.exchanges)) {
    return false;
  }

  const parsedTx = parseTransactionIdentifier(mtx.transactionId);
  if (parsedTx?.tag === TransactionType.Refresh && !req?.includeRefreshes) {
    return false;
  }

  let included: boolean;

  const filter = req?.filterByState;
  switch (filter) {
    case "done":
      included =
        mtx.status >= OPERATION_STATUS_DONE_FIRST &&
        mtx.status <= OPERATION_STATUS_DONE_LAST;
      break;
    case "final":
      included = !(
        mtx.status >= OPERATION_STATUS_NONFINAL_FIRST &&
        mtx.status <= OPERATION_STATUS_NONFINAL_LAST
      );
      break;
    case "nonfinal":
      included =
        mtx.status >= OPERATION_STATUS_NONFINAL_FIRST &&
        mtx.status <= OPERATION_STATUS_NONFINAL_LAST;
      break;
    case undefined:
      included = true;
      break;
    default:
      assertUnreachable(filter);
  }
  return included;
}

async function addFiltered(
  wex: WalletExecutionContext,
  tx: WalletDbAllStoresReadOnlyTransaction,
  req: GetTransactionsV2Request | undefined,
  target: Transaction[],
  source: TransactionMetaRecord[],
): Promise<number> {
  let numAdded: number = 0;
  for (const mtx of source) {
    if (req?.limit != null && target.length >= Math.abs(req.limit)) {
      break;
    }
    if (checkFilterIncludes(req, mtx)) {
      const ctx = await getContextForTransaction(wex, mtx.transactionId);
      const txDetails = await ctx.lookupFullTransaction(tx);
      // FIXME: This means that in some cases we can return fewer transactions
      // than requested.
      if (!txDetails) {
        continue;
      }
      numAdded += 1;
      target.push(txDetails);
    }
  }
  return numAdded;
}

/**
 * Sort transactions in-place according to the request.
 */
function sortTransactions(
  req: GetTransactionsV2Request | undefined,
  transactions: Transaction[],
): void {
  let sortSign: number;
  if (req?.limit != null && req.limit < 0) {
    sortSign = -1;
  } else {
    sortSign = 1;
  }
  const txCmp = (h1: Transaction, h2: Transaction) => {
    // Order transactions by timestamp.  Newest transactions come first.
    const tsCmp = AbsoluteTime.cmp(
      AbsoluteTime.fromPreciseTimestamp(h1.timestamp),
      AbsoluteTime.fromPreciseTimestamp(h2.timestamp),
    );
    // If the timestamp is exactly the same, order by transaction type.
    if (tsCmp === 0) {
      return Math.sign(txOrder[h1.type] - txOrder[h2.type]);
    }
    return sortSign * tsCmp;
  };
  transactions.sort(txCmp);
}

async function findOffsetTransaction(
  tx: WalletDbAllStoresReadOnlyTransaction,
  req?: GetTransactionsV2Request,
): Promise<TransactionMetaRecord | undefined> {
  let forwards = req?.limit == null || req.limit >= 0;
  let closestTimestamp: DbPreciseTimestamp | undefined = undefined;
  if (req?.offsetTransactionId) {
    const res = await tx.transactionsMeta.get(req.offsetTransactionId);
    if (res) {
      return res;
    }
    if (req.offsetTimestamp) {
      closestTimestamp = timestampPreciseToDb(req.offsetTimestamp);
    } else {
      throw Error(
        "offset transaction not found and no offset timestamp specified",
      );
    }
  } else if (req?.offsetTimestamp) {
    const dbStamp = timestampPreciseToDb(req.offsetTimestamp);
    const res = await tx.transactionsMeta.indexes.byTimestamp.get(dbStamp);
    if (res) {
      return res;
    }
    closestTimestamp = timestampPreciseToDb(req.offsetTimestamp);
  } else {
    return undefined;
  }

  // We didn't find a precise offset transaction.
  // This must mean that it was deleted.
  // Depending on the direction, find the prev/next
  // transaction and use it as an offset.

  if (forwards) {
    // We don't want to skip transactions in pagination,
    // so get the transaction before the timestamp

    // Slow query, but should not happen often!
    const recs = await tx.transactionsMeta.indexes.byTimestamp.getAll(
      BridgeIDBKeyRange.upperBound(closestTimestamp, false),
    );
    if (recs.length > 0) {
      return recs[recs.length - 1];
    }
    return undefined;
  } else {
    // Likewise, get the transaction after the timestamp
    const recs = await tx.transactionsMeta.indexes.byTimestamp.getAll(
      BridgeIDBKeyRange.lowerBound(closestTimestamp, false),
      1,
    );
    return recs[0];
  }
}

export async function getTransactionsV2(
  wex: WalletExecutionContext,
  transactionsRequest?: GetTransactionsV2Request,
): Promise<TransactionsResponse> {
  // The implementation of this function is optimized for
  // the common fast path of requesting transactions
  // in an ascending order.
  // Other requests are more difficult to implement
  // in a performant way due to IndexedDB limitations.

  const resultTransactions: Transaction[] = [];

  await wex.db.runAllStoresReadOnlyTx({}, async (tx) => {
    let forwards =
      transactionsRequest?.limit == null || transactionsRequest.limit >= 0;
    let limit =
      transactionsRequest?.limit != null
        ? Math.abs(transactionsRequest.limit)
        : undefined;
    let offsetMtx = await findOffsetTransaction(tx, transactionsRequest);

    if (limit == null && offsetMtx == null) {
      // Fast path for returning *everything* that matches the filter.
      // FIXME: We could use the DB for filtering here
      const res = await tx.transactionsMeta.indexes.byStatus.getAll();
      await addFiltered(wex, tx, transactionsRequest, resultTransactions, res);
    } else if (!forwards) {
      // Descending, backwards request.
      // Slow implementation. Doing it properly would require using cursors,
      // which are also slow in IndexedDB.
      const res = await tx.transactionsMeta.indexes.byTimestamp.getAll();
      res.reverse();
      let start: number;
      if (offsetMtx != null) {
        const needleTxId = offsetMtx.transactionId;
        start = res.findIndex((x) => x.transactionId === needleTxId);
        if (start < 0) {
          throw Error("offset transaction not found");
        }
      } else {
        start = 0;
      }
      for (let i = start; i < res.length; i++) {
        if (limit != null && resultTransactions.length >= limit) {
          break;
        }
        await addFiltered(wex, tx, transactionsRequest, resultTransactions, [
          res[i],
        ]);
      }
    } else {
      // Forward request
      let query: BridgeIDBKeyRange | undefined = undefined;
      if (offsetMtx != null) {
        query = GlobalIDB.KeyRange.lowerBound(offsetMtx.timestamp, true);
      }
      while (true) {
        const res = await tx.transactionsMeta.indexes.byTimestamp.getAll(
          query,
          limit,
        );
        if (res.length === 0) {
          break;
        }
        await addFiltered(
          wex,
          tx,
          transactionsRequest,
          resultTransactions,
          res,
        );
        if (limit != null && resultTransactions.length >= limit) {
          break;
        }
        // Continue after last result
        query = BridgeIDBKeyRange.lowerBound(
          res[res.length - 1].timestamp,
          true,
        );
      }
    }
  });

  sortTransactions(transactionsRequest, resultTransactions);

  return {
    transactions: resultTransactions,
  };
}

/**
 * Retrieve the full event history for this wallet.
 */
export async function getTransactions(
  wex: WalletExecutionContext,
  transactionsRequest?: TransactionsRequest,
): Promise<TransactionsResponse> {
  const transactions: Transaction[] = [];

  let keyRange: IDBKeyRange | undefined = undefined;

  if (transactionsRequest?.filterByState === "nonfinal") {
    keyRange = GlobalIDB.KeyRange.bound(
      OPERATION_STATUS_NONFINAL_FIRST,
      OPERATION_STATUS_NONFINAL_LAST,
    );
  }

  await wex.db.runAllStoresReadOnlyTx({}, async (tx) => {
    const allMetaTransactions =
      await tx.transactionsMeta.indexes.byStatus.getAll(keyRange);
    for (const metaTx of allMetaTransactions) {
      if (
        shouldSkipCurrency(
          transactionsRequest,
          metaTx.currency,
          metaTx.exchanges,
        )
      ) {
        continue;
      }

      const parsedTx = parseTransactionIdentifier(metaTx.transactionId);
      if (
        parsedTx?.tag === TransactionType.Refresh &&
        !transactionsRequest?.includeRefreshes
      ) {
        continue;
      }

      const ctx = await getContextForTransaction(wex, metaTx.transactionId);
      const txDetails = await ctx.lookupFullTransaction(tx);
      if (!txDetails) {
        continue;
      }
      transactions.push(txDetails);
    }
  });

  // One-off checks, because of a bug where the wallet previously
  // did not migrate the DB correctly and caused these amounts
  // to be missing sometimes.
  for (let tx of transactions) {
    if (!tx.amountEffective) {
      logger.warn(`missing amountEffective in ${j2s(tx)}`);
    }
    if (!tx.amountRaw) {
      logger.warn(`missing amountRaw in ${j2s(tx)}`);
    }
    if (!tx.timestamp) {
      logger.warn(`missing timestamp in ${j2s(tx)}`);
    }
  }

  const isPending = (x: Transaction) =>
    x.txState.major === TransactionMajorState.Pending ||
    x.txState.major === TransactionMajorState.Aborting ||
    x.txState.major === TransactionMajorState.Dialog;

  let sortSign: number;
  if (transactionsRequest?.sort == "descending") {
    sortSign = -1;
  } else {
    sortSign = 1;
  }

  const txCmp = (h1: Transaction, h2: Transaction) => {
    // Order transactions by timestamp.  Newest transactions come first.
    const tsCmp = AbsoluteTime.cmp(
      AbsoluteTime.fromPreciseTimestamp(h1.timestamp),
      AbsoluteTime.fromPreciseTimestamp(h2.timestamp),
    );
    // If the timestamp is exactly the same, order by transaction type.
    if (tsCmp === 0) {
      return Math.sign(txOrder[h1.type] - txOrder[h2.type]);
    }
    return sortSign * tsCmp;
  };

  if (transactionsRequest?.sort === "stable-ascending") {
    transactions.sort(txCmp);
    return { transactions };
  }

  const txPending = transactions.filter((x) => isPending(x));
  const txNotPending = transactions.filter((x) => !isPending(x));

  txPending.sort(txCmp);
  txNotPending.sort(txCmp);

  return { transactions: [...txPending, ...txNotPending] };
}

/**
 * Re-create materialized transactions from scratch.
 *
 * Used for migrations.
 */
export async function rematerializeTransactions(
  wex: WalletExecutionContext,
  tx: WalletDbAllStoresReadWriteTransaction,
): Promise<void> {
  logger.info("re-materializing transactions");

  const allTxMeta = await tx.transactionsMeta.getAll();
  for (const txMeta of allTxMeta) {
    await tx.transactionsMeta.delete(txMeta.transactionId);
  }

  await tx.peerPushDebit.iter().forEachAsync(async (x) => {
    const ctx = new PeerPushDebitTransactionContext(wex, x.pursePub);
    await ctx.updateTransactionMeta(tx);
  });

  await tx.peerPushCredit.iter().forEachAsync(async (x) => {
    const ctx = new PeerPushCreditTransactionContext(wex, x.peerPushCreditId);
    await ctx.updateTransactionMeta(tx);
  });

  await tx.peerPullCredit.iter().forEachAsync(async (x) => {
    const ctx = new PeerPullCreditTransactionContext(wex, x.pursePub);
    await ctx.updateTransactionMeta(tx);
  });

  await tx.peerPullDebit.iter().forEachAsync(async (x) => {
    const ctx = new PeerPullDebitTransactionContext(wex, x.peerPullDebitId);
    await ctx.updateTransactionMeta(tx);
  });

  await tx.refundGroups.iter().forEachAsync(async (x) => {
    const ctx = new RefundTransactionContext(wex, x.refundGroupId);
    await ctx.updateTransactionMeta(tx);
  });

  await tx.refreshGroups.iter().forEachAsync(async (x) => {
    const ctx = new RefreshTransactionContext(wex, x.refreshGroupId);
    await ctx.updateTransactionMeta(tx);
  });

  await tx.withdrawalGroups.iter().forEachAsync(async (x) => {
    const ctx = new WithdrawTransactionContext(wex, x.withdrawalGroupId);
    await ctx.updateTransactionMeta(tx);
  });

  await tx.denomLossEvents.iter().forEachAsync(async (x) => {
    const ctx = new DenomLossTransactionContext(wex, x.denomLossEventId);
    await ctx.updateTransactionMeta(tx);
  });

  await tx.depositGroups.iter().forEachAsync(async (x) => {
    const ctx = new DepositTransactionContext(wex, x.depositGroupId);
    await ctx.updateTransactionMeta(tx);
  });

  await tx.purchases.iter().forEachAsync(async (x) => {
    const ctx = new PayMerchantTransactionContext(wex, x.proposalId);
    await ctx.updateTransactionMeta(tx);
  });
}

export type ParsedTransactionIdentifier =
  | { tag: TransactionType.Deposit; depositGroupId: string }
  | { tag: TransactionType.Payment; proposalId: string }
  | { tag: TransactionType.PeerPullDebit; peerPullDebitId: string }
  | { tag: TransactionType.PeerPullCredit; pursePub: string }
  | { tag: TransactionType.PeerPushCredit; peerPushCreditId: string }
  | { tag: TransactionType.PeerPushDebit; pursePub: string }
  | { tag: TransactionType.Refresh; refreshGroupId: string }
  | { tag: TransactionType.Refund; refundGroupId: string }
  | { tag: TransactionType.Withdrawal; withdrawalGroupId: string }
  | { tag: TransactionType.InternalWithdrawal; withdrawalGroupId: string }
  | { tag: TransactionType.Recoup; recoupGroupId: string }
  | { tag: TransactionType.DenomLoss; denomLossEventId: string };

export function constructTransactionIdentifier(
  pTxId: ParsedTransactionIdentifier,
): TransactionIdStr {
  switch (pTxId.tag) {
    case TransactionType.Deposit:
      return `txn:${pTxId.tag}:${pTxId.depositGroupId}` as TransactionIdStr;
    case TransactionType.Payment:
      return `txn:${pTxId.tag}:${pTxId.proposalId}` as TransactionIdStr;
    case TransactionType.PeerPullCredit:
      return `txn:${pTxId.tag}:${pTxId.pursePub}` as TransactionIdStr;
    case TransactionType.PeerPullDebit:
      return `txn:${pTxId.tag}:${pTxId.peerPullDebitId}` as TransactionIdStr;
    case TransactionType.PeerPushCredit:
      return `txn:${pTxId.tag}:${pTxId.peerPushCreditId}` as TransactionIdStr;
    case TransactionType.PeerPushDebit:
      return `txn:${pTxId.tag}:${pTxId.pursePub}` as TransactionIdStr;
    case TransactionType.Refresh:
      return `txn:${pTxId.tag}:${pTxId.refreshGroupId}` as TransactionIdStr;
    case TransactionType.Refund:
      return `txn:${pTxId.tag}:${pTxId.refundGroupId}` as TransactionIdStr;
    case TransactionType.Withdrawal:
      return `txn:${pTxId.tag}:${pTxId.withdrawalGroupId}` as TransactionIdStr;
    case TransactionType.InternalWithdrawal:
      return `txn:${pTxId.tag}:${pTxId.withdrawalGroupId}` as TransactionIdStr;
    case TransactionType.Recoup:
      return `txn:${pTxId.tag}:${pTxId.recoupGroupId}` as TransactionIdStr;
    case TransactionType.DenomLoss:
      return `txn:${pTxId.tag}:${pTxId.denomLossEventId}` as TransactionIdStr;
    default:
      assertUnreachable(pTxId);
  }
}

/**
 * Parse a transaction identifier string into a typed, structured representation.
 */
export function parseTransactionIdentifier(
  transactionId: string,
): ParsedTransactionIdentifier | undefined {
  const txnParts = transactionId.split(":");

  if (txnParts.length < 3) {
    throw Error("id should have al least 3 parts separated by ':'");
  }

  const [prefix, type, ...rest] = txnParts;

  if (prefix != "txn") {
    throw Error("invalid transaction identifier");
  }

  switch (type) {
    case TransactionType.Deposit:
      return { tag: TransactionType.Deposit, depositGroupId: rest[0] };
    case TransactionType.Payment:
      return { tag: TransactionType.Payment, proposalId: rest[0] };
    case TransactionType.PeerPullCredit:
      return { tag: TransactionType.PeerPullCredit, pursePub: rest[0] };
    case TransactionType.PeerPullDebit:
      return {
        tag: TransactionType.PeerPullDebit,
        peerPullDebitId: rest[0],
      };
    case TransactionType.PeerPushCredit:
      return {
        tag: TransactionType.PeerPushCredit,
        peerPushCreditId: rest[0],
      };
    case TransactionType.PeerPushDebit:
      return { tag: TransactionType.PeerPushDebit, pursePub: rest[0] };
    case TransactionType.Refresh:
      return { tag: TransactionType.Refresh, refreshGroupId: rest[0] };
    case TransactionType.Refund:
      return {
        tag: TransactionType.Refund,
        refundGroupId: rest[0],
      };
    case TransactionType.Withdrawal:
      return {
        tag: TransactionType.Withdrawal,
        withdrawalGroupId: rest[0],
      };
    case TransactionType.DenomLoss:
      return {
        tag: TransactionType.DenomLoss,
        denomLossEventId: rest[0],
      };
    default:
      return undefined;
  }
}

function maybeTaskFromTransaction(
  transactionId: string,
): TaskIdStr | undefined {
  const parsedTx = parseTransactionIdentifier(transactionId);

  if (!parsedTx) {
    throw Error("invalid transaction identifier");
  }

  // FIXME: We currently don't cancel active long-polling tasks here.

  switch (parsedTx.tag) {
    case TransactionType.PeerPullCredit:
      return constructTaskIdentifier({
        tag: PendingTaskType.PeerPullCredit,
        pursePub: parsedTx.pursePub,
      });
    case TransactionType.Deposit:
      return constructTaskIdentifier({
        tag: PendingTaskType.Deposit,
        depositGroupId: parsedTx.depositGroupId,
      });
    case TransactionType.InternalWithdrawal:
    case TransactionType.Withdrawal:
      return constructTaskIdentifier({
        tag: PendingTaskType.Withdraw,
        withdrawalGroupId: parsedTx.withdrawalGroupId,
      });
    case TransactionType.Payment:
      return constructTaskIdentifier({
        tag: PendingTaskType.Purchase,
        proposalId: parsedTx.proposalId,
      });
    case TransactionType.Refresh:
      return constructTaskIdentifier({
        tag: PendingTaskType.Refresh,
        refreshGroupId: parsedTx.refreshGroupId,
      });
    case TransactionType.PeerPullDebit:
      return constructTaskIdentifier({
        tag: PendingTaskType.PeerPullDebit,
        peerPullDebitId: parsedTx.peerPullDebitId,
      });
    case TransactionType.PeerPushCredit:
      return constructTaskIdentifier({
        tag: PendingTaskType.PeerPushCredit,
        peerPushCreditId: parsedTx.peerPushCreditId,
      });
    case TransactionType.PeerPushDebit:
      return constructTaskIdentifier({
        tag: PendingTaskType.PeerPushDebit,
        pursePub: parsedTx.pursePub,
      });
    case TransactionType.Refund:
      // Nothing to do for a refund transaction.
      return undefined;
    case TransactionType.Recoup:
      return constructTaskIdentifier({
        tag: PendingTaskType.Recoup,
        recoupGroupId: parsedTx.recoupGroupId,
      });
    case TransactionType.DenomLoss:
      // Nothing to do for denom loss
      return undefined;
    default:
      assertUnreachable(parsedTx);
  }
}

/**
 * Immediately retry the underlying operation
 * of a transaction.
 */
export async function retryTransaction(
  wex: WalletExecutionContext,
  transactionId: string,
): Promise<void> {
  logger.info(`resetting retry timeout for ${transactionId}`);
  const taskId = maybeTaskFromTransaction(transactionId);
  if (taskId) {
    await wex.taskScheduler.resetTaskRetries(taskId);
  }
}

/**
 * Reset the task retry counter for all tasks.
 */
export async function retryAll(wex: WalletExecutionContext): Promise<void> {
  await wex.taskScheduler.ensureRunning();
  const tasks = wex.taskScheduler.getActiveTasks();
  for (const task of tasks) {
    await wex.taskScheduler.resetTaskRetries(task);
  }
}

/**
 * Restart all the running tasks.
 */
export async function restartAll(wex: WalletExecutionContext): Promise<void> {
  await wex.taskScheduler.reload();
}

async function getContextForTransaction(
  wex: WalletExecutionContext,
  transactionId: string,
): Promise<TransactionContext> {
  const tx = parseTransactionIdentifier(transactionId);
  if (!tx) {
    throw Error("invalid transaction ID");
  }
  switch (tx.tag) {
    case TransactionType.Deposit:
      return new DepositTransactionContext(wex, tx.depositGroupId);
    case TransactionType.Refresh:
      return new RefreshTransactionContext(wex, tx.refreshGroupId);
    case TransactionType.InternalWithdrawal:
    case TransactionType.Withdrawal:
      return new WithdrawTransactionContext(wex, tx.withdrawalGroupId);
    case TransactionType.Payment:
      return new PayMerchantTransactionContext(wex, tx.proposalId);
    case TransactionType.PeerPullCredit:
      return new PeerPullCreditTransactionContext(wex, tx.pursePub);
    case TransactionType.PeerPushDebit:
      return new PeerPushDebitTransactionContext(wex, tx.pursePub);
    case TransactionType.PeerPullDebit:
      return new PeerPullDebitTransactionContext(wex, tx.peerPullDebitId);
    case TransactionType.PeerPushCredit:
      return new PeerPushCreditTransactionContext(wex, tx.peerPushCreditId);
    case TransactionType.Refund:
      return new RefundTransactionContext(wex, tx.refundGroupId);
    case TransactionType.Recoup:
      //return new RecoupTransactionContext(ws, tx.recoupGroupId);
      throw new Error("not yet supported");
    case TransactionType.DenomLoss:
      return new DenomLossTransactionContext(wex, tx.denomLossEventId);
    default:
      assertUnreachable(tx);
  }
}

/**
 * Suspends a pending transaction, stopping any associated network activities,
 * but with a chance of trying again at a later time. This could be useful if
 * a user needs to save battery power or bandwidth and an operation is expected
 * to take longer (such as a backup, recovery or very large withdrawal operation).
 */
export async function suspendTransaction(
  wex: WalletExecutionContext,
  transactionId: string,
): Promise<void> {
  const ctx = await getContextForTransaction(wex, transactionId);
  await ctx.suspendTransaction();
}

export async function failTransaction(
  wex: WalletExecutionContext,
  transactionId: string,
): Promise<void> {
  const ctx = await getContextForTransaction(wex, transactionId);
  await ctx.failTransaction(
    makeTalerErrorDetail(
      TalerErrorCode.WALLET_TRANSACTION_ABANDONED_BY_USER,
      {},
    ),
  );
}

/**
 * Resume a suspended transaction.
 */
export async function resumeTransaction(
  wex: WalletExecutionContext,
  transactionId: string,
): Promise<void> {
  const ctx = await getContextForTransaction(wex, transactionId);
  await ctx.resumeTransaction();
}

/**
 * Permanently delete a transaction based on the transaction ID.
 */
export async function deleteTransaction(
  wex: WalletExecutionContext,
  transactionId: string,
): Promise<void> {
  const ctx = await getContextForTransaction(wex, transactionId);
  await ctx.deleteTransaction();
  if (ctx.taskId) {
    wex.taskScheduler.stopShepherdTask(ctx.taskId);
  }
}

export async function abortTransaction(
  wex: WalletExecutionContext,
  transactionId: string,
): Promise<void> {
  const ctx = await getContextForTransaction(wex, transactionId);
  await ctx.abortTransaction(
    makeTalerErrorDetail(TalerErrorCode.WALLET_TRANSACTION_ABORTED_BY_USER, {}),
  );
}

export interface TransitionInfo {
  oldTxState: TransactionState;
  newTxState: TransactionState;
}

/**
 * Notify of a state transition if necessary.
 */
export function notifyTransition(
  wex: WalletExecutionContext,
  transactionId: string,
  transitionInfo: TransitionInfo | undefined,
  experimentalUserData: any = undefined,
): void {
  if (
    transitionInfo &&
    !(
      transitionInfo.oldTxState.major === transitionInfo.newTxState.major &&
      transitionInfo.oldTxState.minor === transitionInfo.newTxState.minor
    )
  ) {
    wex.ws.notify({
      type: NotificationType.TransactionStateTransition,
      oldTxState: transitionInfo.oldTxState,
      newTxState: transitionInfo.newTxState,
      transactionId,
      experimentalUserData,
    });

    // As a heuristic, we emit balance-change notifications
    // whenever the major state changes.
    // This sometimes emits more notifications than we need,
    // but makes it much more unlikely that we miss any.
    if (transitionInfo.newTxState.major !== transitionInfo.oldTxState.major) {
      wex.ws.notify({
        type: NotificationType.BalanceChange,
        hintTransactionId: transactionId,
      });
    }
  }
}