aboutsummaryrefslogtreecommitdiff
path: root/src/operations/tip.ts
blob: 17f7ee90d7daa66acf3f21360501547811bf7896 (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
/*
 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/>
 */

import { InternalWalletState } from "./state";
import { parseTipUri } from "../util/taleruri";
import { TipStatus, OperationErrorDetails } from "../types/walletTypes";
import {
  TipPlanchetDetail,
  codecForTipPickupGetResponse,
  codecForTipResponse,
} from "../types/talerTypes";
import * as Amounts from "../util/amounts";
import {
  Stores,
  PlanchetRecord,
  WithdrawalGroupRecord,
  initRetryInfo,
  updateRetryInfoTimeout,
  WithdrawalSourceType,
  TipPlanchet,
} from "../types/dbTypes";
import {
  getExchangeWithdrawalInfo,
  selectWithdrawalDenoms,
  processWithdrawGroup,
  denomSelectionInfoToState,
} from "./withdraw";
import { updateExchangeFromUrl } from "./exchanges";
import { getRandomBytes, encodeCrock } from "../crypto/talerCrypto";
import { guardOperationException } from "./errors";
import { NotificationType } from "../types/notifications";
import { getTimestampNow } from "../util/time";
import { readSuccessResponseJsonOrThrow } from "../util/http";

export async function getTipStatus(
  ws: InternalWalletState,
  talerTipUri: string,
): Promise<TipStatus> {
  const res = parseTipUri(talerTipUri);
  if (!res) {
    throw Error("invalid taler://tip URI");
  }

  const tipStatusUrl = new URL("tip-pickup", res.merchantBaseUrl);
  tipStatusUrl.searchParams.set("tip_id", res.merchantTipId);
  console.log("checking tip status from", tipStatusUrl.href);
  const merchantResp = await ws.http.get(tipStatusUrl.href);
  const tipPickupStatus = await readSuccessResponseJsonOrThrow(
    merchantResp,
    codecForTipPickupGetResponse(),
  );
  console.log("status", tipPickupStatus);

  const amount = Amounts.parseOrThrow(tipPickupStatus.amount);

  const merchantOrigin = new URL(res.merchantBaseUrl).origin;

  let tipRecord = await ws.db.get(Stores.tips, [
    res.merchantTipId,
    merchantOrigin,
  ]);

  if (!tipRecord) {
    await updateExchangeFromUrl(ws, tipPickupStatus.exchange_url);
    const withdrawDetails = await getExchangeWithdrawalInfo(
      ws,
      tipPickupStatus.exchange_url,
      amount,
    );

    const tipId = encodeCrock(getRandomBytes(32));
    const selectedDenoms = await selectWithdrawalDenoms(
      ws,
      tipPickupStatus.exchange_url,
      amount,
    );

    tipRecord = {
      tipId,
      acceptedTimestamp: undefined,
      rejectedTimestamp: undefined,
      amount,
      deadline: tipPickupStatus.stamp_expire,
      exchangeUrl: tipPickupStatus.exchange_url,
      merchantBaseUrl: res.merchantBaseUrl,
      nextUrl: undefined,
      pickedUp: false,
      planchets: undefined,
      response: undefined,
      createdTimestamp: getTimestampNow(),
      merchantTipId: res.merchantTipId,
      totalFees: Amounts.add(
        withdrawDetails.overhead,
        withdrawDetails.withdrawFee,
      ).amount,
      retryInfo: initRetryInfo(),
      lastError: undefined,
      denomsSel: denomSelectionInfoToState(selectedDenoms),
    };
    await ws.db.put(Stores.tips, tipRecord);
  }

  const tipStatus: TipStatus = {
    accepted: !!tipRecord && !!tipRecord.acceptedTimestamp,
    amount: Amounts.parseOrThrow(tipPickupStatus.amount),
    amountLeft: Amounts.parseOrThrow(tipPickupStatus.amount_left),
    exchangeUrl: tipPickupStatus.exchange_url,
    nextUrl: tipPickupStatus.extra.next_url,
    merchantOrigin: merchantOrigin,
    merchantTipId: res.merchantTipId,
    expirationTimestamp: tipPickupStatus.stamp_expire,
    timestamp: tipPickupStatus.stamp_created,
    totalFees: tipRecord.totalFees,
    tipId: tipRecord.tipId,
  };

  return tipStatus;
}

async function incrementTipRetry(
  ws: InternalWalletState,
  refreshSessionId: string,
  err: OperationErrorDetails | undefined,
): Promise<void> {
  await ws.db.runWithWriteTransaction([Stores.tips], async (tx) => {
    const t = await tx.get(Stores.tips, refreshSessionId);
    if (!t) {
      return;
    }
    if (!t.retryInfo) {
      return;
    }
    t.retryInfo.retryCounter++;
    updateRetryInfoTimeout(t.retryInfo);
    t.lastError = err;
    await tx.put(Stores.tips, t);
  });
  ws.notify({ type: NotificationType.TipOperationError });
}

export async function processTip(
  ws: InternalWalletState,
  tipId: string,
  forceNow = false,
): Promise<void> {
  const onOpErr = (e: OperationErrorDetails): Promise<void> =>
    incrementTipRetry(ws, tipId, e);
  await guardOperationException(
    () => processTipImpl(ws, tipId, forceNow),
    onOpErr,
  );
}

async function resetTipRetry(
  ws: InternalWalletState,
  tipId: string,
): Promise<void> {
  await ws.db.mutate(Stores.tips, tipId, (x) => {
    if (x.retryInfo.active) {
      x.retryInfo = initRetryInfo();
    }
    return x;
  });
}

async function processTipImpl(
  ws: InternalWalletState,
  tipId: string,
  forceNow: boolean,
): Promise<void> {
  if (forceNow) {
    await resetTipRetry(ws, tipId);
  }
  let tipRecord = await ws.db.get(Stores.tips, tipId);
  if (!tipRecord) {
    return;
  }

  if (tipRecord.pickedUp) {
    console.log("tip already picked up");
    return;
  }

  const denomsForWithdraw = tipRecord.denomsSel;

  if (!tipRecord.planchets) {
    const planchets: TipPlanchet[] = [];

    for (const sd of denomsForWithdraw.selectedDenoms) {
      const denom = await ws.db.getIndexed(
        Stores.denominations.denomPubHashIndex,
        sd.denomPubHash,
      );
      if (!denom) {
        throw Error("denom does not exist anymore");
      }
      for (let i = 0; i < sd.count; i++) {
        const r = await ws.cryptoApi.createTipPlanchet(denom);
        planchets.push(r);
      }
    }
    await ws.db.mutate(Stores.tips, tipId, (r) => {
      if (!r.planchets) {
        r.planchets = planchets;
      }
      return r;
    });
  }

  tipRecord = await ws.db.get(Stores.tips, tipId);
  if (!tipRecord) {
    throw Error("tip not in database");
  }

  if (!tipRecord.planchets) {
    throw Error("invariant violated");
  }

  console.log("got planchets for tip!");

  // Planchets in the form that the merchant expects
  const planchetsDetail: TipPlanchetDetail[] = tipRecord.planchets.map((p) => ({
    coin_ev: p.coinEv,
    denom_pub_hash: p.denomPubHash,
  }));

  let merchantResp;

  const tipStatusUrl = new URL("tip-pickup", tipRecord.merchantBaseUrl);

  try {
    const req = { planchets: planchetsDetail, tip_id: tipRecord.merchantTipId };
    merchantResp = await ws.http.postJson(tipStatusUrl.href, req);
    if (merchantResp.status !== 200) {
      throw Error(`unexpected status ${merchantResp.status} for tip-pickup`);
    }
    console.log("got merchant resp:", merchantResp);
  } catch (e) {
    console.log("tipping failed", e);
    throw e;
  }

  const response = codecForTipResponse().decode(await merchantResp.json());

  if (response.reserve_sigs.length !== tipRecord.planchets.length) {
    throw Error("number of tip responses does not match requested planchets");
  }

  const withdrawalGroupId = encodeCrock(getRandomBytes(32));
  const planchets: PlanchetRecord[] = [];

  for (let i = 0; i < tipRecord.planchets.length; i++) {
    const tipPlanchet = tipRecord.planchets[i];
    const coinEvHash = await ws.cryptoApi.hashEncoded(tipPlanchet.coinEv);
    const planchet: PlanchetRecord = {
      blindingKey: tipPlanchet.blindingKey,
      coinEv: tipPlanchet.coinEv,
      coinPriv: tipPlanchet.coinPriv,
      coinPub: tipPlanchet.coinPub,
      coinValue: tipPlanchet.coinValue,
      denomPub: tipPlanchet.denomPub,
      denomPubHash: tipPlanchet.denomPubHash,
      reservePub: response.reserve_pub,
      withdrawSig: response.reserve_sigs[i].reserve_sig,
      isFromTip: true,
      coinEvHash,
      coinIdx: i,
      withdrawalDone: false,
      withdrawalGroupId: withdrawalGroupId,
    };
    planchets.push(planchet);
  }

  const withdrawalGroup: WithdrawalGroupRecord = {
    exchangeBaseUrl: tipRecord.exchangeUrl,
    source: {
      type: WithdrawalSourceType.Tip,
      tipId: tipRecord.tipId,
    },
    timestampStart: getTimestampNow(),
    withdrawalGroupId: withdrawalGroupId,
    rawWithdrawalAmount: tipRecord.amount,
    lastErrorPerCoin: {},
    retryInfo: initRetryInfo(),
    timestampFinish: undefined,
    lastError: undefined,
    denomsSel: tipRecord.denomsSel,
  };

  await ws.db.runWithWriteTransaction(
    [Stores.tips, Stores.withdrawalGroups],
    async (tx) => {
      const tr = await tx.get(Stores.tips, tipId);
      if (!tr) {
        return;
      }
      if (tr.pickedUp) {
        return;
      }
      tr.pickedUp = true;
      tr.retryInfo = initRetryInfo(false);

      await tx.put(Stores.tips, tr);
      await tx.put(Stores.withdrawalGroups, withdrawalGroup);
      for (const p of planchets) {
        await tx.put(Stores.planchets, p);
      }
    },
  );

  await processWithdrawGroup(ws, withdrawalGroupId);
}

export async function acceptTip(
  ws: InternalWalletState,
  tipId: string,
): Promise<void> {
  const tipRecord = await ws.db.get(Stores.tips, tipId);
  if (!tipRecord) {
    console.log("tip not found");
    return;
  }

  tipRecord.acceptedTimestamp = getTimestampNow();
  await ws.db.put(Stores.tips, tipRecord);

  await processTip(ws, tipId);
  return;
}