aboutsummaryrefslogtreecommitdiff
path: root/src/wallet-impl/pay.ts
blob: d4d2b3cd4543a02203c1812118c292edbe82e1be (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
/*
 This file is part of GNU Taler
 (C) 2019 GNUnet e.V.

 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/>
 */

import { AmountJson } from "../util/amounts";
import {
  Auditor,
  ExchangeHandle,
  MerchantRefundResponse,
  PayReq,
  Proposal,
  ContractTerms,
} from "../talerTypes";
import {
  Timestamp,
  CoinSelectionResult,
  CoinWithDenom,
  PayCoinInfo,
  getTimestampNow,
  PreparePayResult,
  ConfirmPayResult,
} from "../walletTypes";
import {
  oneShotIter,
  oneShotIterIndex,
  oneShotGet,
  runWithWriteTransaction,
  oneShotPut,
  oneShotGetIndexed,
} from "../util/query";
import {
  Stores,
  CoinStatus,
  DenominationRecord,
  ProposalRecord,
  PurchaseRecord,
  CoinRecord,
  ProposalStatus,
} from "../dbTypes";
import * as Amounts from "../util/amounts";
import {
  amountToPretty,
  strcmp,
  extractTalerStamp,
  canonicalJson,
} from "../util/helpers";
import { Logger } from "../util/logging";
import { InternalWalletState } from "./state";
import { parsePayUri } from "../util/taleruri";
import { getTotalRefreshCost, refresh } from "./refresh";
import { acceptRefundResponse } from "./refund";
import { encodeCrock, getRandomBytes } from "../crypto/talerCrypto";

export interface SpeculativePayData {
  payCoinInfo: PayCoinInfo;
  exchangeUrl: string;
  orderDownloadId: string;
  proposal: ProposalRecord;
}

interface CoinsForPaymentArgs {
  allowedAuditors: Auditor[];
  allowedExchanges: ExchangeHandle[];
  depositFeeLimit: AmountJson;
  paymentAmount: AmountJson;
  wireFeeAmortization: number;
  wireFeeLimit: AmountJson;
  wireFeeTime: Timestamp;
  wireMethod: string;
}

interface SelectPayCoinsResult {
  cds: CoinWithDenom[];
  totalFees: AmountJson;
}

const logger = new Logger("pay.ts");

/**
 * Select coins for a payment under the merchant's constraints.
 *
 * @param denoms all available denoms, used to compute refresh fees
 */
export function selectPayCoins(
  denoms: DenominationRecord[],
  cds: CoinWithDenom[],
  paymentAmount: AmountJson,
  depositFeeLimit: AmountJson,
): SelectPayCoinsResult | undefined {
  if (cds.length === 0) {
    return undefined;
  }
  // Sort by ascending deposit fee and denomPub if deposit fee is the same
  // (to guarantee deterministic results)
  cds.sort(
    (o1, o2) =>
      Amounts.cmp(o1.denom.feeDeposit, o2.denom.feeDeposit) ||
      strcmp(o1.denom.denomPub, o2.denom.denomPub),
  );
  const currency = cds[0].denom.value.currency;
  const cdsResult: CoinWithDenom[] = [];
  let accDepositFee: AmountJson = Amounts.getZero(currency);
  let accAmount: AmountJson = Amounts.getZero(currency);
  for (const { coin, denom } of cds) {
    if (coin.suspended) {
      continue;
    }
    if (coin.status !== CoinStatus.Fresh) {
      continue;
    }
    if (Amounts.cmp(denom.feeDeposit, coin.currentAmount) >= 0) {
      continue;
    }
    cdsResult.push({ coin, denom });
    accDepositFee = Amounts.add(denom.feeDeposit, accDepositFee).amount;
    let leftAmount = Amounts.sub(
      coin.currentAmount,
      Amounts.sub(paymentAmount, accAmount).amount,
    ).amount;
    accAmount = Amounts.add(coin.currentAmount, accAmount).amount;
    const coversAmount = Amounts.cmp(accAmount, paymentAmount) >= 0;
    const coversAmountWithFee =
      Amounts.cmp(
        accAmount,
        Amounts.add(paymentAmount, denom.feeDeposit).amount,
      ) >= 0;
    const isBelowFee = Amounts.cmp(accDepositFee, depositFeeLimit) <= 0;

    logger.trace("candidate coin selection", {
      coversAmount,
      isBelowFee,
      accDepositFee,
      accAmount,
      paymentAmount,
    });

    if ((coversAmount && isBelowFee) || coversAmountWithFee) {
      const depositFeeToCover = Amounts.sub(accDepositFee, depositFeeLimit)
        .amount;
      leftAmount = Amounts.sub(leftAmount, depositFeeToCover).amount;
      logger.trace("deposit fee to cover", amountToPretty(depositFeeToCover));
      let totalFees: AmountJson = Amounts.getZero(currency);
      if (coversAmountWithFee && !isBelowFee) {
        // these are the fees the customer has to pay
        // because the merchant doesn't cover them
        totalFees = Amounts.sub(depositFeeLimit, accDepositFee).amount;
      }
      totalFees = Amounts.add(
        totalFees,
        getTotalRefreshCost(denoms, denom, leftAmount),
      ).amount;
      return { cds: cdsResult, totalFees };
    }
  }
  return undefined;
}

/**
 * Get exchanges and associated coins that are still spendable, but only
 * if the sum the coins' remaining value covers the payment amount and fees.
 */
async function getCoinsForPayment(
  ws: InternalWalletState,
  args: CoinsForPaymentArgs,
): Promise<CoinSelectionResult | undefined> {
  const {
    allowedAuditors,
    allowedExchanges,
    depositFeeLimit,
    paymentAmount,
    wireFeeAmortization,
    wireFeeLimit,
    wireFeeTime,
    wireMethod,
  } = args;

  let remainingAmount = paymentAmount;

  const exchanges = await oneShotIter(ws.db, Stores.exchanges).toArray();

  for (const exchange of exchanges) {
    let isOkay: boolean = false;
    const exchangeDetails = exchange.details;
    if (!exchangeDetails) {
      continue;
    }
    const exchangeFees = exchange.wireInfo;
    if (!exchangeFees) {
      continue;
    }

    // is the exchange explicitly allowed?
    for (const allowedExchange of allowedExchanges) {
      if (allowedExchange.master_pub === exchangeDetails.masterPublicKey) {
        isOkay = true;
        break;
      }
    }

    // is the exchange allowed because of one of its auditors?
    if (!isOkay) {
      for (const allowedAuditor of allowedAuditors) {
        for (const auditor of exchangeDetails.auditors) {
          if (auditor.auditor_pub === allowedAuditor.auditor_pub) {
            isOkay = true;
            break;
          }
        }
        if (isOkay) {
          break;
        }
      }
    }

    if (!isOkay) {
      continue;
    }

    const coins = await oneShotIterIndex(
      ws.db,
      Stores.coins.exchangeBaseUrlIndex,
      exchange.baseUrl,
    ).toArray();

    const denoms = await oneShotIterIndex(
      ws.db,
      Stores.denominations.exchangeBaseUrlIndex,
      exchange.baseUrl,
    ).toArray();

    if (!coins || coins.length === 0) {
      continue;
    }

    // Denomination of the first coin, we assume that all other
    // coins have the same currency
    const firstDenom = await oneShotGet(ws.db, Stores.denominations, [
      exchange.baseUrl,
      coins[0].denomPub,
    ]);
    if (!firstDenom) {
      throw Error("db inconsistent");
    }
    const currency = firstDenom.value.currency;
    const cds: CoinWithDenom[] = [];
    for (const coin of coins) {
      const denom = await oneShotGet(ws.db, Stores.denominations, [
        exchange.baseUrl,
        coin.denomPub,
      ]);
      if (!denom) {
        throw Error("db inconsistent");
      }
      if (denom.value.currency !== currency) {
        console.warn(
          `same pubkey for different currencies at exchange ${exchange.baseUrl}`,
        );
        continue;
      }
      if (coin.suspended) {
        continue;
      }
      if (coin.status !== CoinStatus.Fresh) {
        continue;
      }
      cds.push({ coin, denom });
    }

    let totalFees = Amounts.getZero(currency);
    let wireFee: AmountJson | undefined;
    for (const fee of exchangeFees.feesForType[wireMethod] || []) {
      if (fee.startStamp <= wireFeeTime && fee.endStamp >= wireFeeTime) {
        wireFee = fee.wireFee;
        break;
      }
    }

    if (wireFee) {
      const amortizedWireFee = Amounts.divide(wireFee, wireFeeAmortization);
      if (Amounts.cmp(wireFeeLimit, amortizedWireFee) < 0) {
        totalFees = Amounts.add(amortizedWireFee, totalFees).amount;
        remainingAmount = Amounts.add(amortizedWireFee, remainingAmount).amount;
      }
    }

    const res = selectPayCoins(denoms, cds, remainingAmount, depositFeeLimit);

    if (res) {
      totalFees = Amounts.add(totalFees, res.totalFees).amount;
      return {
        cds: res.cds,
        exchangeUrl: exchange.baseUrl,
        totalAmount: remainingAmount,
        totalFees,
      };
    }
  }
  return undefined;
}

/**
 * Record all information that is necessary to
 * pay for a proposal in the wallet's database.
 */
async function recordConfirmPay(
  ws: InternalWalletState,
  proposal: ProposalRecord,
  payCoinInfo: PayCoinInfo,
  chosenExchange: string,
): Promise<PurchaseRecord> {
  const payReq: PayReq = {
    coins: payCoinInfo.sigs,
    merchant_pub: proposal.contractTerms.merchant_pub,
    mode: "pay",
    order_id: proposal.contractTerms.order_id,
  };
  const t: PurchaseRecord = {
    abortDone: false,
    abortRequested: false,
    contractTerms: proposal.contractTerms,
    contractTermsHash: proposal.contractTermsHash,
    finished: false,
    lastSessionId: undefined,
    merchantSig: proposal.merchantSig,
    payReq,
    refundsDone: {},
    refundsPending: {},
    timestamp: getTimestampNow(),
    timestamp_refund: undefined,
  };

  await runWithWriteTransaction(
    ws.db,
    [Stores.coins, Stores.purchases],
    async tx => {
      await tx.put(Stores.purchases, t);
      for (let c of payCoinInfo.updatedCoins) {
        await tx.put(Stores.coins, c);
      }
    },
  );

  ws.badge.showNotification();
  ws.notifier.notify();
  return t;
}

function getNextUrl(contractTerms: ContractTerms): string {
  const fu = new URL(contractTerms.fulfillment_url)
  fu.searchParams.set("order_id", contractTerms.order_id);
  return fu.href;
}

export async function abortFailedPayment(
  ws: InternalWalletState,
  contractTermsHash: string,
): Promise<void> {
  const purchase = await oneShotGet(ws.db, Stores.purchases, contractTermsHash);
  if (!purchase) {
    throw Error("Purchase not found, unable to abort with refund");
  }
  if (purchase.finished) {
    throw Error("Purchase already finished, not aborting");
  }
  if (purchase.abortDone) {
    console.warn("abort requested on already aborted purchase");
    return;
  }

  purchase.abortRequested = true;

  // From now on, we can't retry payment anymore,
  // so mark this in the DB in case the /pay abort
  // does not complete on the first try.
  await oneShotPut(ws.db, Stores.purchases, purchase);

  let resp;

  const abortReq = { ...purchase.payReq, mode: "abort-refund" };

  const payUrl = new URL("pay", purchase.contractTerms.merchant_base_url).href;

  try {
    resp = await ws.http.postJson(payUrl, abortReq);
  } catch (e) {
    // Gives the user the option to retry / abort and refresh
    console.log("aborting payment failed", e);
    throw e;
  }

  const refundResponse = MerchantRefundResponse.checked(resp.responseJson);
  await acceptRefundResponse(ws, refundResponse);

  await runWithWriteTransaction(ws.db, [Stores.purchases], async tx => {
    const p = await tx.get(Stores.purchases, purchase.contractTermsHash);
    if (!p) {
      return;
    }
    p.abortDone = true;
    await tx.put(Stores.purchases, p);
  });
}

/**
 * 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.
 */
async function downloadProposal(
  ws: InternalWalletState,
  url: string,
  sessionId?: string,
): Promise<string> {
  const oldProposal = await oneShotGetIndexed(
    ws.db,
    Stores.proposals.urlIndex,
    url,
  );
  if (oldProposal) {
    return oldProposal.proposalId;
  }

  const { priv, pub } = await ws.cryptoApi.createEddsaKeypair();
  const parsed_url = new URL(url);
  parsed_url.searchParams.set("nonce", pub);
  const urlWithNonce = parsed_url.href;
  console.log("downloading contract from '" + urlWithNonce + "'");
  let resp;
  try {
    resp = await ws.http.get(urlWithNonce);
  } catch (e) {
    console.log("contract download failed", e);
    throw e;
  }

  const proposal = Proposal.checked(resp.responseJson);

  const contractTermsHash = await ws.cryptoApi.hashString(
    canonicalJson(proposal.contract_terms),
  );

  const proposalId = encodeCrock(getRandomBytes(32));

  const proposalRecord: ProposalRecord = {
    contractTerms: proposal.contract_terms,
    contractTermsHash,
    merchantSig: proposal.sig,
    noncePriv: priv,
    timestamp: getTimestampNow(),
    url,
    downloadSessionId: sessionId,
    proposalId: proposalId,
    proposalStatus: ProposalStatus.PROPOSED,
  };
  await oneShotPut(ws.db, Stores.proposals, proposalRecord);
  ws.notifier.notify();

  return proposalId;
}

async function submitPay(
  ws: InternalWalletState,
  contractTermsHash: string,
  sessionId: string | undefined,
): Promise<ConfirmPayResult> {
  const purchase = await oneShotGet(ws.db, Stores.purchases, contractTermsHash);
  if (!purchase) {
    throw Error("Purchase not found: " + contractTermsHash);
  }
  if (purchase.abortRequested) {
    throw Error("not submitting payment for aborted purchase");
  }
  let resp;
  const payReq = { ...purchase.payReq, session_id: sessionId };

  const payUrl = new URL("pay", purchase.contractTerms.merchant_base_url).href;

  try {
    resp = await ws.http.postJson(payUrl, payReq);
  } catch (e) {
    // Gives the user the option to retry / abort and refresh
    console.log("payment failed", e);
    throw e;
  }
  const merchantResp = resp.responseJson;
  console.log("got success from pay URL");

  const merchantPub = purchase.contractTerms.merchant_pub;
  const valid: boolean = await ws.cryptoApi.isValidPaymentSignature(
    merchantResp.sig,
    contractTermsHash,
    merchantPub,
  );
  if (!valid) {
    console.error("merchant payment signature invalid");
    // FIXME: properly display error
    throw Error("merchant payment signature invalid");
  }
  purchase.finished = true;
  const modifiedCoins: CoinRecord[] = [];
  for (const pc of purchase.payReq.coins) {
    const c = await oneShotGet(ws.db, Stores.coins, pc.coin_pub);
    if (!c) {
      console.error("coin not found");
      throw Error("coin used in payment not found");
    }
    c.status = CoinStatus.Dirty;
    modifiedCoins.push(c);
  }

  await runWithWriteTransaction(
    ws.db,
    [Stores.coins, Stores.purchases],
    async tx => {
      for (let c of modifiedCoins) {
        tx.put(Stores.coins, c);
      }
      tx.put(Stores.purchases, purchase);
    },
  );

  for (const c of purchase.payReq.coins) {
    refresh(ws, c.coin_pub);
  }

  const nextUrl = getNextUrl(purchase.contractTerms);
  ws.cachedNextUrl[purchase.contractTerms.fulfillment_url] = {
    nextUrl,
    lastSessionId: sessionId,
  };

  return { nextUrl };
}

/**
 * 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 preparePay(
  ws: InternalWalletState,
  talerPayUri: string,
): Promise<PreparePayResult> {
  const uriResult = parsePayUri(talerPayUri);

  if (!uriResult) {
    return {
      status: "error",
      error: "URI not supported",
    };
  }

  let proposalId: string;
  try {
    proposalId = await downloadProposal(
      ws,
      uriResult.downloadUrl,
      uriResult.sessionId,
    );
  } catch (e) {
    return {
      status: "error",
      error: e.toString(),
    };
  }
  const proposal = await oneShotGet(ws.db, Stores.proposals, proposalId);
  if (!proposal) {
    throw Error(`could not get proposal ${proposalId}`);
  }

  console.log("proposal", proposal);

  const differentPurchase = await oneShotGetIndexed(
    ws.db,
    Stores.purchases.fulfillmentUrlIndex,
    proposal.contractTerms.fulfillment_url,
  );

  let fulfillmentUrl = proposal.contractTerms.fulfillment_url;
  let doublePurchaseDetection = false;
  if (fulfillmentUrl.startsWith("http")) {
    doublePurchaseDetection = true;
  }

  if (differentPurchase && doublePurchaseDetection) {
    // We do this check to prevent merchant B to find out if we bought a
    // digital product with merchant A by abusing the existing payment
    // redirect feature.
    if (
      differentPurchase.contractTerms.merchant_pub !=
      proposal.contractTerms.merchant_pub
    ) {
      console.warn(
        "merchant with different public key offered contract with same fulfillment URL as an existing purchase",
      );
    } else {
      if (uriResult.sessionId) {
        await submitPay(
          ws,
          differentPurchase.contractTermsHash,
          uriResult.sessionId,
        );
      }
      return {
        status: "paid",
        contractTerms: differentPurchase.contractTerms,
        nextUrl: getNextUrl(differentPurchase.contractTerms),
      };
    }
  }

  // First check if we already payed for it.
  const purchase = await oneShotGet(
    ws.db,
    Stores.purchases,
    proposal.contractTermsHash,
  );

  if (!purchase) {
    const paymentAmount = Amounts.parseOrThrow(proposal.contractTerms.amount);
    let wireFeeLimit;
    if (proposal.contractTerms.max_wire_fee) {
      wireFeeLimit = Amounts.parseOrThrow(proposal.contractTerms.max_wire_fee);
    } else {
      wireFeeLimit = Amounts.getZero(paymentAmount.currency);
    }
    // If not already payed, check if we could pay for it.
    const res = await getCoinsForPayment(ws, {
      allowedAuditors: proposal.contractTerms.auditors,
      allowedExchanges: proposal.contractTerms.exchanges,
      depositFeeLimit: Amounts.parseOrThrow(proposal.contractTerms.max_fee),
      paymentAmount,
      wireFeeAmortization: proposal.contractTerms.wire_fee_amortization || 1,
      wireFeeLimit,
      // FIXME: parse this properly
      wireFeeTime: extractTalerStamp(proposal.contractTerms.timestamp) || {
        t_ms: 0,
      },
      wireMethod: proposal.contractTerms.wire_method,
    });

    if (!res) {
      console.log("not confirming payment, insufficient coins");
      return {
        status: "insufficient-balance",
        contractTerms: proposal.contractTerms,
        proposalId: proposal.proposalId,
      };
    }

    // Only create speculative signature if we don't already have one for this proposal
    if (
      !ws.speculativePayData ||
      (ws.speculativePayData &&
        ws.speculativePayData.orderDownloadId !== proposalId)
    ) {
      const { exchangeUrl, cds, totalAmount } = res;
      const payCoinInfo = await ws.cryptoApi.signDeposit(
        proposal.contractTerms,
        cds,
        totalAmount,
      );
      ws.speculativePayData = {
        exchangeUrl,
        payCoinInfo,
        proposal,
        orderDownloadId: proposalId,
      };
      logger.trace("created speculative pay data for payment");
    }

    return {
      status: "payment-possible",
      contractTerms: proposal.contractTerms,
      proposalId: proposal.proposalId,
      totalFees: res.totalFees,
    };
  }

  if (uriResult.sessionId) {
    await submitPay(ws, purchase.contractTermsHash, uriResult.sessionId);
  }

  return {
    status: "paid",
    contractTerms: proposal.contractTerms,
    nextUrl: getNextUrl(purchase.contractTerms),
  };
}

/**
 * Get the speculative pay data, but only if coins have not changed in between.
 */
async function getSpeculativePayData(
  ws: InternalWalletState,
  proposalId: string,
): Promise<SpeculativePayData | undefined> {
  const sp = ws.speculativePayData;
  if (!sp) {
    return;
  }
  if (sp.orderDownloadId !== proposalId) {
    return;
  }
  const coinKeys = sp.payCoinInfo.updatedCoins.map(x => x.coinPub);
  const coins: CoinRecord[] = [];
  for (let coinKey of coinKeys) {
    const cc = await oneShotGet(ws.db, Stores.coins, coinKey);
    if (cc) {
      coins.push(cc);
    }
  }
  for (let i = 0; i < coins.length; i++) {
    const specCoin = sp.payCoinInfo.originalCoins[i];
    const currentCoin = coins[i];

    // Coin does not exist anymore!
    if (!currentCoin) {
      return;
    }
    if (Amounts.cmp(specCoin.currentAmount, currentCoin.currentAmount) !== 0) {
      return;
    }
  }
  return sp;
}

/**
 * Add a contract to the wallet and sign coins, and send them.
 */
export async function confirmPay(
  ws: InternalWalletState,
  proposalId: string,
  sessionIdOverride: string | undefined,
): Promise<ConfirmPayResult> {
  logger.trace(
    `executing confirmPay with proposalId ${proposalId} and sessionIdOverride ${sessionIdOverride}`,
  );
  const proposal = await oneShotGet(ws.db, Stores.proposals, proposalId);

  if (!proposal) {
    throw Error(`proposal with id ${proposalId} not found`);
  }

  const sessionId = sessionIdOverride || proposal.downloadSessionId;

  let purchase = await oneShotGet(
    ws.db,
    Stores.purchases,
    proposal.contractTermsHash,
  );

  if (purchase) {
    return submitPay(ws, purchase.contractTermsHash, sessionId);
  }

  const contractAmount = Amounts.parseOrThrow(proposal.contractTerms.amount);

  let wireFeeLimit;
  if (!proposal.contractTerms.max_wire_fee) {
    wireFeeLimit = Amounts.getZero(contractAmount.currency);
  } else {
    wireFeeLimit = Amounts.parseOrThrow(proposal.contractTerms.max_wire_fee);
  }

  const res = await getCoinsForPayment(ws, {
    allowedAuditors: proposal.contractTerms.auditors,
    allowedExchanges: proposal.contractTerms.exchanges,
    depositFeeLimit: Amounts.parseOrThrow(proposal.contractTerms.max_fee),
    paymentAmount: Amounts.parseOrThrow(proposal.contractTerms.amount),
    wireFeeAmortization: proposal.contractTerms.wire_fee_amortization || 1,
    wireFeeLimit,
    // FIXME: parse this properly
    wireFeeTime: extractTalerStamp(proposal.contractTerms.timestamp) || {
      t_ms: 0,
    },
    wireMethod: proposal.contractTerms.wire_method,
  });

  logger.trace("coin selection result", res);

  if (!res) {
    // Should not happen, since checkPay should be called first
    console.log("not confirming payment, insufficient coins");
    throw Error("insufficient balance");
  }

  const sd = await getSpeculativePayData(ws, proposalId);
  if (!sd) {
    const { exchangeUrl, cds, totalAmount } = res;
    const payCoinInfo = await ws.cryptoApi.signDeposit(
      proposal.contractTerms,
      cds,
      totalAmount,
    );
    purchase = await recordConfirmPay(ws, proposal, payCoinInfo, exchangeUrl);
  } else {
    purchase = await recordConfirmPay(
      ws,
      sd.proposal,
      sd.payCoinInfo,
      sd.exchangeUrl,
    );
  }

  return submitPay(ws, purchase.contractTermsHash, sessionId);
}