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
|
/*
This file is part of GNU Taler
(C) 2021 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/>
*/
/**
* Helper functions to run wallet functionality (withdrawal, deposit, refresh)
* without a database or retry loop.
*
* Used for benchmarking, where we want to benchmark the exchange, but the
* normal wallet would be too sluggish.
*/
/**
* Imports.
*/
import {
AbsoluteTime,
AgeRestriction,
AmountJson,
Amounts,
AmountString,
TalerCorebankApiClient,
codecForAny,
codecForBankWithdrawalOperationPostResponse,
codecForBatchDepositSuccess,
codecForExchangeMeltResponse,
codecForExchangeRevealResponse,
codecForWithdrawResponse,
DenominationPubKey,
encodeCrock,
ExchangeBatchDepositRequest,
ExchangeMeltRequest,
ExchangeProtocolVersion,
ExchangeWithdrawRequest,
getRandomBytes,
hashWire,
Logger,
parsePaytoUri,
UnblindedSignature,
ExchangeBatchWithdrawRequest,
ExchangeWithdrawBatchResponse,
codecForExchangeWithdrawBatchResponse,
} from "@gnu-taler/taler-util";
import {
HttpRequestLibrary,
readSuccessResponseJsonOrThrow,
} from "@gnu-taler/taler-util/http";
import { TalerCryptoInterface } from "./crypto/cryptoImplementation.js";
import { DenominationRecord } from "./db.js";
import { isWithdrawableDenom } from "./index.js";
import { ExchangeInfo } from "./operations/exchanges.js";
import { assembleRefreshRevealRequest } from "./operations/refresh.js";
import {
getBankStatusUrl,
getBankWithdrawalInfo,
} from "./operations/withdraw.js";
const logger = new Logger("dbless.ts");
export interface ReserveKeypair {
reservePub: string;
reservePriv: string;
}
/**
* Denormalized info about a coin.
*/
export interface CoinInfo {
coinPub: string;
coinPriv: string;
exchangeBaseUrl: string;
denomSig: UnblindedSignature;
denomPub: DenominationPubKey;
denomPubHash: string;
feeDeposit: string;
feeRefresh: string;
maxAge: number;
}
/**
* Check the status of a reserve, use long-polling to wait
* until the reserve actually has been created.
*/
export async function checkReserve(
http: HttpRequestLibrary,
exchangeBaseUrl: string,
reservePub: string,
longpollTimeoutMs: number = 500,
): Promise<void> {
const reqUrl = new URL(`reserves/${reservePub}`, exchangeBaseUrl);
if (longpollTimeoutMs) {
reqUrl.searchParams.set("timeout_ms", `${longpollTimeoutMs}`);
}
const resp = await http.get(reqUrl.href);
if (resp.status !== 200) {
throw new Error("reserve not okay");
}
}
export interface TopupReserveWithDemobankArgs {
http: HttpRequestLibrary;
reservePub: string;
corebankApiBaseUrl: string;
exchangeInfo: ExchangeInfo;
amount: AmountString;
}
export async function topupReserveWithDemobank(
args: TopupReserveWithDemobankArgs,
) {
const { http, corebankApiBaseUrl, amount, exchangeInfo, reservePub } = args;
const bankClient = new TalerCorebankApiClient(corebankApiBaseUrl);
const bankUser = await bankClient.createRandomBankUser();
const wopi = await bankClient.createWithdrawalOperation(
bankUser.username,
amount,
);
const bankInfo = await getBankWithdrawalInfo(http, wopi.taler_withdraw_uri);
const bankStatusUrl = getBankStatusUrl(wopi.taler_withdraw_uri);
if (!bankInfo.suggestedExchange) {
throw Error("no suggested exchange");
}
const plainPaytoUris =
exchangeInfo.keys.accounts.map((x) => x.payto_uri) ?? [];
if (plainPaytoUris.length <= 0) {
throw new Error();
}
const httpResp = await http.postJson(bankStatusUrl, {
reserve_pub: reservePub,
selected_exchange: plainPaytoUris[0],
});
await readSuccessResponseJsonOrThrow(
httpResp,
codecForBankWithdrawalOperationPostResponse(),
);
await bankClient.confirmWithdrawalOperation(bankUser.username, {
withdrawalOperationId: wopi.withdrawal_id,
});
}
export async function withdrawCoin(args: {
http: HttpRequestLibrary;
cryptoApi: TalerCryptoInterface;
reserveKeyPair: ReserveKeypair;
denom: DenominationRecord;
exchangeBaseUrl: string;
}): Promise<CoinInfo> {
const { http, cryptoApi, reserveKeyPair, denom, exchangeBaseUrl } = args;
const planchet = await cryptoApi.createPlanchet({
coinIndex: 0,
denomPub: denom.denomPub,
feeWithdraw: Amounts.parseOrThrow(denom.fees.feeWithdraw),
reservePriv: reserveKeyPair.reservePriv,
reservePub: reserveKeyPair.reservePub,
secretSeed: encodeCrock(getRandomBytes(32)),
value: Amounts.parseOrThrow(denom.value),
});
const reqBody: ExchangeBatchWithdrawRequest = {
planchets: [
{
denom_pub_hash: planchet.denomPubHash,
reserve_sig: planchet.withdrawSig,
coin_ev: planchet.coinEv,
},
],
};
const reqUrl = new URL(
`reserves/${planchet.reservePub}/batch-withdraw`,
exchangeBaseUrl,
).href;
const resp = await http.fetch(reqUrl, { method: "POST", body: reqBody });
const rBatch = await readSuccessResponseJsonOrThrow(
resp,
codecForExchangeWithdrawBatchResponse(),
);
const ubSig = await cryptoApi.unblindDenominationSignature({
planchet,
evSig: rBatch.ev_sigs[0].ev_sig,
});
return {
coinPriv: planchet.coinPriv,
coinPub: planchet.coinPub,
denomSig: ubSig,
denomPub: denom.denomPub,
denomPubHash: denom.denomPubHash,
feeDeposit: Amounts.stringify(denom.fees.feeDeposit),
feeRefresh: Amounts.stringify(denom.fees.feeRefresh),
exchangeBaseUrl: args.exchangeBaseUrl,
maxAge: AgeRestriction.AGE_UNRESTRICTED,
};
}
export interface FindDenomOptions {
denomselAllowLate?: boolean;
}
export function findDenomOrThrow(
exchangeInfo: ExchangeInfo,
amount: AmountString,
options: FindDenomOptions = {},
): DenominationRecord {
const denomselAllowLate = options.denomselAllowLate ?? false;
for (const d of exchangeInfo.keys.currentDenominations) {
const value: AmountJson = Amounts.parseOrThrow(d.value);
if (
Amounts.cmp(value, amount) === 0 &&
isWithdrawableDenom(d, denomselAllowLate)
) {
return d;
}
}
throw new Error("no matching denomination found");
}
export async function depositCoin(args: {
http: HttpRequestLibrary;
cryptoApi: TalerCryptoInterface;
exchangeBaseUrl: string;
coin: CoinInfo;
amount: AmountString;
depositPayto?: string;
merchantPub?: string;
contractTermsHash?: string;
// 16 bytes, crockford encoded
wireSalt?: string;
}): Promise<void> {
const { coin, http, cryptoApi } = args;
const depositPayto =
args.depositPayto ?? "payto://x-taler-bank/localhost/foo";
const wireSalt = args.wireSalt ?? encodeCrock(getRandomBytes(16));
const timestampNow = AbsoluteTime.toProtocolTimestamp(AbsoluteTime.now());
const contractTermsHash =
args.contractTermsHash ?? encodeCrock(getRandomBytes(64));
const depositTimestamp = timestampNow;
const refundDeadline = timestampNow;
const wireTransferDeadline = timestampNow;
const merchantPub = args.merchantPub ?? encodeCrock(getRandomBytes(32));
const dp = await cryptoApi.signDepositPermission({
coinPriv: coin.coinPriv,
coinPub: coin.coinPub,
contractTermsHash,
denomKeyType: coin.denomPub.cipher,
denomPubHash: coin.denomPubHash,
denomSig: coin.denomSig,
exchangeBaseUrl: args.exchangeBaseUrl,
feeDeposit: Amounts.parseOrThrow(coin.feeDeposit),
merchantPub,
spendAmount: Amounts.parseOrThrow(args.amount),
timestamp: depositTimestamp,
refundDeadline: refundDeadline,
wireInfoHash: hashWire(depositPayto, wireSalt),
});
const requestBody: ExchangeBatchDepositRequest = {
coins: [
{
contribution: Amounts.stringify(dp.contribution),
coin_pub: dp.coin_pub,
coin_sig: dp.coin_sig,
denom_pub_hash: dp.h_denom,
ub_sig: dp.ub_sig,
},
],
merchant_payto_uri: depositPayto,
wire_salt: wireSalt,
h_contract_terms: contractTermsHash,
timestamp: depositTimestamp,
wire_transfer_deadline: wireTransferDeadline,
refund_deadline: refundDeadline,
merchant_pub: merchantPub,
};
const url = new URL(`batch-deposit`, dp.exchange_url);
const httpResp = await http.fetch(url.href, {
method: "POST",
body: requestBody,
});
await readSuccessResponseJsonOrThrow(httpResp, codecForBatchDepositSuccess());
}
export async function refreshCoin(req: {
http: HttpRequestLibrary;
cryptoApi: TalerCryptoInterface;
oldCoin: CoinInfo;
newDenoms: DenominationRecord[];
}): Promise<void> {
const { cryptoApi, oldCoin, http } = req;
const refreshSessionSeed = encodeCrock(getRandomBytes(32));
const session = await cryptoApi.deriveRefreshSession({
exchangeProtocolVersion: ExchangeProtocolVersion.V12,
feeRefresh: Amounts.parseOrThrow(oldCoin.feeRefresh),
kappa: 3,
meltCoinDenomPubHash: oldCoin.denomPubHash,
meltCoinPriv: oldCoin.coinPriv,
meltCoinPub: oldCoin.coinPub,
sessionSecretSeed: refreshSessionSeed,
newCoinDenoms: req.newDenoms.map((x) => ({
count: 1,
denomPub: x.denomPub,
denomPubHash: x.denomPubHash,
feeWithdraw: x.fees.feeWithdraw,
value: x.value,
})),
meltCoinMaxAge: oldCoin.maxAge,
});
const meltReqBody: ExchangeMeltRequest = {
coin_pub: oldCoin.coinPub,
confirm_sig: session.confirmSig,
denom_pub_hash: oldCoin.denomPubHash,
denom_sig: oldCoin.denomSig,
rc: session.hash,
value_with_fee: Amounts.stringify(session.meltValueWithFee),
};
logger.info("requesting melt");
const meltReqUrl = new URL(
`coins/${oldCoin.coinPub}/melt`,
oldCoin.exchangeBaseUrl,
);
logger.info("requesting melt done");
const meltHttpResp = await http.fetch(meltReqUrl.href, {
method: "POST",
body: meltReqBody,
});
const meltResponse = await readSuccessResponseJsonOrThrow(
meltHttpResp,
codecForExchangeMeltResponse(),
);
const norevealIndex = meltResponse.noreveal_index;
const revealRequest = await assembleRefreshRevealRequest({
cryptoApi,
derived: session,
newDenoms: req.newDenoms.map((x) => ({
count: 1,
denomPubHash: x.denomPubHash,
})),
norevealIndex,
oldCoinPriv: oldCoin.coinPriv,
oldCoinPub: oldCoin.coinPub,
});
logger.info("requesting reveal");
const reqUrl = new URL(
`refreshes/${session.hash}/reveal`,
oldCoin.exchangeBaseUrl,
);
const revealResp = await http.postJson(reqUrl.href, revealRequest);
logger.info("requesting reveal done");
const reveal = await readSuccessResponseJsonOrThrow(
revealResp,
codecForExchangeRevealResponse(),
);
// We could unblind here, but we only use this function to
// benchmark the exchange.
}
/**
* Create a reserve for testing withdrawals.
*
* The reserve is created using the test-only API "/admin/add-incoming".
*/
export async function createTestingReserve(args: {
http: HttpRequestLibrary;
corebankApiBaseUrl: string;
amount: string;
reservePub: string;
exchangeInfo: ExchangeInfo;
}): Promise<void> {
const { http, corebankApiBaseUrl, amount, reservePub } = args;
const paytoUri = args.exchangeInfo.keys.accounts[0].payto_uri;
const pt = parsePaytoUri(paytoUri);
if (!pt) {
throw Error("failed to parse payto URI");
}
const components = pt.targetPath.split("/");
const creditorAcct = components[components.length - 1];
const fbReq = await http.fetch(
new URL(
`taler-wire-gateway/${creditorAcct}/admin/add-incoming`,
corebankApiBaseUrl,
).href,
{
method: "POST",
body: {
amount,
reserve_pub: reservePub,
debit_account: "payto://x-taler-bank/localhost/testdebtor",
},
},
);
await readSuccessResponseJsonOrThrow(fbReq, codecForAny());
}
|