wallet-core/src/headless/taler-wallet-cli.ts

932 lines
28 KiB
TypeScript
Raw Normal View History

2019-08-01 23:27:42 +02:00
/*
This file is part of GNU Taler
(C) 2019 Taler Systems S.A.
2019-08-01 23:27:42 +02:00
GNU Taler is free software; you can redistribute it and/or modify it under the
2019-08-01 23:27:42 +02:00
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
2019-08-01 23:27:42 +02:00
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/>
2019-08-01 23:27:42 +02:00
*/
import os from "os";
import fs from "fs";
2019-08-16 23:29:29 +02:00
import { getDefaultNodeWallet, withdrawTestBalance } from "./helpers";
import { MerchantBackendConnection } from "./merchant";
2020-03-23 12:30:01 +01:00
import { runIntegrationTest, runIntegrationTestBasic } from "./integrationtest";
2019-12-05 19:38:19 +01:00
import { Wallet } from "../wallet";
import qrcodeGenerator from "qrcode-generator";
2019-11-19 16:16:12 +01:00
import * as clk from "./clk";
2020-04-07 10:07:32 +02:00
import { BridgeIDBFactory } from "idb-bridge";
import { Logger } from "../util/logging";
import { Amounts } from "../util/amounts";
2020-06-21 14:50:39 +02:00
import {
decodeCrock,
setupRefreshPlanchet,
encodeCrock,
} from "../crypto/talerCrypto";
import { OperationFailedAndReportedError } from "../operations/errors";
2019-12-06 00:56:31 +01:00
import { Bank } from "./bank";
2019-12-06 12:47:28 +01:00
import { classifyTalerUri, TalerUriType } from "../util/taleruri";
2020-03-23 12:30:01 +01:00
import { Configuration } from "../util/talerconfig";
2020-03-23 13:17:35 +01:00
import { setDangerousTimetravel } from "../util/time";
2020-03-24 10:55:04 +01:00
import { makeCodecForList, codecForString } from "../util/codec";
2020-03-24 19:24:32 +01:00
import { NodeHttpLib } from "./NodeHttpLib";
2020-06-08 16:02:38 +02:00
import * as nacl from "../crypto/primitives/nacl-fast";
2020-06-21 14:49:27 +02:00
import { addPaytoQueryParams } from "../util/payto";
2020-02-24 18:40:36 +01:00
2019-11-21 23:09:43 +01:00
const logger = new Logger("taler-wallet-cli.ts");
2019-08-16 23:29:29 +02:00
2020-03-23 12:30:01 +01:00
const defaultWalletDbPath = os.homedir + "/" + ".talerwalletdb.json";
2019-08-16 23:29:29 +02:00
2019-11-30 00:36:20 +01:00
function assertUnreachable(x: never): never {
throw new Error("Didn't expect to get here");
}
2019-11-19 16:16:12 +01:00
async function doPay(
wallet: Wallet,
payUrl: string,
options: { alwaysYes: boolean } = { alwaysYes: true },
2020-04-07 10:07:32 +02:00
): Promise<void> {
2019-12-20 01:25:22 +01:00
const result = await wallet.preparePayForUri(payUrl);
2019-11-19 16:16:12 +01:00
if (result.status === "error") {
console.error("Could not pay:", result.error);
process.exit(1);
return;
}
if (result.status === "insufficient-balance") {
console.log("contract", result.contractTermsRaw);
2019-11-19 16:16:12 +01:00
console.error("insufficient balance");
process.exit(1);
return;
}
if (result.status === "paid") {
console.log("already paid!");
process.exit(0);
return;
}
if (result.status === "payment-possible") {
console.log("paying ...");
} else {
throw Error("not reached");
}
console.log("contract", result.contractTermsRaw);
console.log("total fees:", Amounts.stringify(result.totalFees));
2019-11-19 16:16:12 +01:00
let pay;
if (options.alwaysYes) {
pay = true;
} else {
while (true) {
const yesNoResp = (await clk.prompt("Pay? [Y/n]")).toLowerCase();
if (yesNoResp === "" || yesNoResp === "y" || yesNoResp === "yes") {
pay = true;
break;
} else if (yesNoResp === "n" || yesNoResp === "no") {
pay = false;
break;
} else {
console.log("please answer y/n");
}
}
}
if (pay) {
2020-04-07 10:07:32 +02:00
await wallet.confirmPay(result.proposalId, undefined);
2019-11-19 16:16:12 +01:00
console.log("paid!");
} else {
console.log("not paying");
}
}
2020-04-07 10:07:32 +02:00
function applyVerbose(verbose: boolean): void {
2019-08-18 23:06:27 +02:00
if (verbose) {
console.log("enabled verbose logging");
2019-11-21 23:09:43 +01:00
BridgeIDBFactory.enableTracing = true;
2019-08-18 23:06:27 +02:00
}
}
2020-04-07 10:07:32 +02:00
function printVersion(): void {
// eslint-disable-next-line @typescript-eslint/no-var-requires
2019-11-30 00:36:20 +01:00
const info = require("../../../package.json");
console.log(`${info.version}`);
process.exit(0);
}
2019-11-19 16:16:12 +01:00
const walletCli = clk
.program("wallet", {
help: "Command line interface for the GNU Taler wallet.",
})
2020-03-23 12:30:01 +01:00
.maybeOption("walletDbFile", ["--wallet-db"], clk.STRING, {
2020-03-24 10:55:04 +01:00
help: "location of the wallet database file",
2020-03-23 12:30:01 +01:00
})
2020-03-23 13:17:35 +01:00
.maybeOption("timetravel", ["--timetravel"], clk.INT, {
help: "modify system time by given offset in microseconds",
onPresentHandler: (x) => {
// Convert microseconds to milliseconds and do timetravel
logger.info(`timetravelling ${x} microseconds`);
setDangerousTimetravel(x / 1000);
},
})
2019-11-19 16:16:12 +01:00
.maybeOption("inhibit", ["--inhibit"], clk.STRING, {
help:
"Inhibit running certain operations, useful for debugging and testing.",
})
2020-03-24 19:24:32 +01:00
.flag("noThrottle", ["--no-throttle"], {
2020-03-27 19:48:25 +01:00
help: "Don't do any request throttling.",
2020-03-24 19:24:32 +01:00
})
2019-11-30 00:36:20 +01:00
.flag("version", ["-v", "--version"], {
onPresentHandler: printVersion,
})
2019-11-19 16:16:12 +01:00
.flag("verbose", ["-V", "--verbose"], {
help: "Enable verbose output.",
});
type WalletCliArgsType = clk.GetArgType<typeof walletCli>;
async function withWallet<T>(
walletCliArgs: WalletCliArgsType,
f: (w: Wallet) => Promise<T>,
): Promise<T> {
2020-03-23 12:30:01 +01:00
const dbPath = walletCliArgs.wallet.walletDbFile ?? defaultWalletDbPath;
2020-03-24 19:24:32 +01:00
const myHttpLib = new NodeHttpLib();
if (walletCliArgs.wallet.noThrottle) {
myHttpLib.setThrottling(false);
}
const wallet = await getDefaultNodeWallet({
2020-03-23 12:30:01 +01:00
persistentStoragePath: dbPath,
2020-03-24 19:24:32 +01:00
httpLib: myHttpLib,
});
2019-11-21 23:09:43 +01:00
applyVerbose(walletCliArgs.wallet.verbose);
try {
await wallet.fillDefaults();
const ret = await f(wallet);
return ret;
} catch (e) {
2019-11-21 23:09:43 +01:00
if (e instanceof OperationFailedAndReportedError) {
console.error("Operation failed: " + e.message);
console.log("Hint: check pending operations for details.");
} else {
2019-12-05 22:17:01 +01:00
console.error("caught unhandled exception (bug?):", e);
2019-11-21 23:09:43 +01:00
}
process.exit(1);
} finally {
wallet.stop();
}
}
2019-11-19 16:16:12 +01:00
walletCli
2019-11-30 00:36:20 +01:00
.subcommand("balance", "balance", { help: "Show wallet balance." })
.flag("json", ["--json"], {
help: "Show raw JSON.",
})
2020-03-24 10:55:04 +01:00
.action(async (args) => {
await withWallet(args, async (wallet) => {
const balance = await wallet.getBalances();
2019-11-30 00:36:20 +01:00
if (args.balance.json) {
console.log(JSON.stringify(balance, undefined, 2));
} else {
const currencies = Object.keys(balance.byCurrency).sort();
for (const c of currencies) {
console.log(Amounts.stringify(balance.byCurrency[c].available));
2019-11-30 00:36:20 +01:00
}
}
});
2019-07-31 01:33:56 +02:00
});
2019-11-19 16:16:12 +01:00
walletCli
.subcommand("history", "history", { help: "Show wallet event history." })
.flag("json", ["--json"], {
default: false,
})
2019-11-21 23:09:43 +01:00
.maybeOption("from", ["--from"], clk.STRING)
.maybeOption("to", ["--to"], clk.STRING)
.maybeOption("limit", ["--limit"], clk.STRING)
.maybeOption("contEvt", ["--continue-with"], clk.STRING)
2020-03-27 19:48:25 +01:00
.flag("extraDebug", ["--extra-debug"])
2020-03-24 10:55:04 +01:00
.action(async (args) => {
await withWallet(args, async (wallet) => {
2020-03-27 19:48:25 +01:00
const history = await wallet.getHistory({
extraDebug: args.history.extraDebug,
});
if (args.history.json) {
console.log(JSON.stringify(history, undefined, 2));
} else {
for (const h of history.history) {
console.log(
2020-03-23 12:30:01 +01:00
`event at ${new Date(h.timestamp.t_ms).toISOString()} with type ${
h.type
}:`,
);
console.log(JSON.stringify(h, undefined, 2));
console.log();
}
}
2019-09-04 14:28:22 +02:00
});
});
2019-11-19 16:16:12 +01:00
walletCli
.subcommand("", "pending", { help: "Show pending operations." })
2020-03-24 10:55:04 +01:00
.action(async (args) => {
await withWallet(args, async (wallet) => {
const pending = await wallet.getPendingOperations();
console.log(JSON.stringify(pending, undefined, 2));
2019-11-19 16:16:12 +01:00
});
});
2020-05-12 10:38:58 +02:00
walletCli
2020-05-15 13:28:15 +02:00
.subcommand("transactions", "transactions", { help: "Show transactions." })
.maybeOption("currency", ["--currency"], clk.STRING)
.maybeOption("search", ["--search"], clk.STRING)
2020-05-12 10:38:58 +02:00
.action(async (args) => {
await withWallet(args, async (wallet) => {
2020-05-15 13:28:15 +02:00
const pending = await wallet.getTransactions({
currency: args.transactions.currency,
search: args.transactions.search,
});
2020-05-12 10:38:58 +02:00
console.log(JSON.stringify(pending, undefined, 2));
});
});
2019-08-20 15:59:05 +02:00
async function asyncSleep(milliSeconds: number): Promise<void> {
return new Promise<void>((resolve, reject) => {
setTimeout(() => resolve(), milliSeconds);
2019-08-20 15:59:05 +02:00
});
}
walletCli
.subcommand("runPendingOpt", "run-pending", {
2019-11-21 23:09:43 +01:00
help: "Run pending operations.",
})
.flag("forceNow", ["-f", "--force-now"])
2020-03-24 10:55:04 +01:00
.action(async (args) => {
await withWallet(args, async (wallet) => {
await wallet.runPending(args.runPendingOpt.forceNow);
});
});
walletCli
.subcommand("finishPendingOpt", "run-until-done", {
help: "Run until no more work is left.",
})
.action(async (args) => {
await withWallet(args, async (wallet) => {
await wallet.runUntilDoneAndStop();
});
});
2019-11-19 16:16:12 +01:00
walletCli
2019-11-21 23:09:43 +01:00
.subcommand("handleUri", "handle-uri", {
help: "Handle a taler:// URI.",
2019-11-19 16:16:12 +01:00
})
2019-11-21 23:09:43 +01:00
.requiredArgument("uri", clk.STRING)
.flag("autoYes", ["-y", "--yes"])
2020-03-24 10:55:04 +01:00
.action(async (args) => {
await withWallet(args, async (wallet) => {
2019-11-21 23:09:43 +01:00
const uri: string = args.handleUri.uri;
2019-12-06 12:47:28 +01:00
const uriType = classifyTalerUri(uri);
switch (uriType) {
case TalerUriType.TalerPay:
await doPay(wallet, uri, { alwaysYes: args.handleUri.autoYes });
break;
case TalerUriType.TalerTip:
{
const res = await wallet.getTipStatus(uri);
console.log("tip status", res);
await wallet.acceptTip(res.tipId);
}
break;
case TalerUriType.TalerRefund:
await wallet.applyRefund(uri);
break;
case TalerUriType.TalerWithdraw:
{
2019-12-09 19:59:08 +01:00
const withdrawInfo = await wallet.getWithdrawDetailsForUri(uri);
const selectedExchange =
withdrawInfo.bankWithdrawDetails.suggestedExchange;
2019-12-06 12:47:28 +01:00
if (!selectedExchange) {
console.error("no suggested exchange!");
process.exit(1);
return;
}
const res = await wallet.acceptWithdrawal(uri, selectedExchange);
await wallet.processReserve(res.reservePub);
}
break;
default:
console.log(`URI type (${uriType}) not handled`);
break;
2019-11-21 23:09:43 +01:00
}
2019-12-06 12:47:28 +01:00
return;
2019-11-21 23:09:43 +01:00
});
});
const exchangesCli = walletCli.subcommand("exchangesCmd", "exchanges", {
help: "Manage exchanges.",
});
exchangesCli
.subcommand("exchangesListCmd", "list", {
help: "List known exchanges.",
})
2020-03-24 10:55:04 +01:00
.action(async (args) => {
2019-11-21 23:09:43 +01:00
console.log("Listing exchanges ...");
2020-03-24 10:55:04 +01:00
await withWallet(args, async (wallet) => {
2019-11-21 23:09:43 +01:00
const exchanges = await wallet.getExchanges();
console.log(JSON.stringify(exchanges, undefined, 2));
2019-11-21 23:09:43 +01:00
});
});
exchangesCli
.subcommand("exchangesUpdateCmd", "update", {
help: "Update or add an exchange by base URL.",
})
.requiredArgument("url", clk.STRING, {
help: "Base URL of the exchange.",
})
.flag("force", ["-f", "--force"])
2020-03-24 10:55:04 +01:00
.action(async (args) => {
await withWallet(args, async (wallet) => {
2020-04-07 10:07:32 +02:00
await wallet.updateExchangeFromUrl(
2019-11-21 23:09:43 +01:00
args.exchangesUpdateCmd.url,
args.exchangesUpdateCmd.force,
);
});
});
exchangesCli
.subcommand("exchangesAddCmd", "add", {
help: "Add an exchange by base URL.",
})
.requiredArgument("url", clk.STRING, {
help: "Base URL of the exchange.",
})
.action(async (args) => {
await withWallet(args, async (wallet) => {
2020-07-16 19:22:56 +02:00
await wallet.updateExchangeFromUrl(args.exchangesAddCmd.url);
});
});
exchangesCli
.subcommand("exchangesAcceptTosCmd", "accept-tos", {
help: "Accept terms of service.",
})
.requiredArgument("url", clk.STRING, {
help: "Base URL of the exchange.",
})
.requiredArgument("etag", clk.STRING, {
help: "ToS version tag to accept",
})
.action(async (args) => {
await withWallet(args, async (wallet) => {
await wallet.acceptExchangeTermsOfService(
args.exchangesAcceptTosCmd.url,
2020-07-16 19:22:56 +02:00
args.exchangesAcceptTosCmd.etag,
);
});
});
2020-07-16 19:22:56 +02:00
exchangesCli
.subcommand("exchangesTosCmd", "tos", {
help: "Show terms of service.",
})
.requiredArgument("url", clk.STRING, {
help: "Base URL of the exchange.",
})
.action(async (args) => {
await withWallet(args, async (wallet) => {
2020-07-16 19:22:56 +02:00
const tosResult = await wallet.getExchangeTos(args.exchangesTosCmd.url);
console.log(JSON.stringify(tosResult, undefined, 2));
});
});
2019-11-21 23:09:43 +01:00
const advancedCli = walletCli.subcommand("advancedArgs", "advanced", {
help:
"Subcommands for advanced operations (only use if you know what you're doing!).",
});
advancedCli
.subcommand("manualWithdrawalDetails", "manual-withdrawal-details", {
help: "Query withdrawal fees.",
})
.requiredArgument("exchange", clk.STRING)
.requiredArgument("amount", clk.STRING)
.action(async (args) => {
await withWallet(args, async (wallet) => {
2020-07-11 09:56:07 +02:00
const details = await wallet.getWithdrawalDetailsForAmount(
args.manualWithdrawalDetails.exchange,
Amounts.parseOrThrow(args.manualWithdrawalDetails.amount),
);
console.log(JSON.stringify(details, undefined, 2));
});
});
advancedCli
.subcommand("decode", "decode", {
2019-11-30 00:36:20 +01:00
help: "Decode base32-crockford.",
})
2020-03-24 10:55:04 +01:00
.action((args) => {
2019-11-30 00:36:20 +01:00
const enc = fs.readFileSync(0, "utf8");
fs.writeFileSync(1, decodeCrock(enc.trim()));
});
2020-06-21 14:49:27 +02:00
advancedCli
2020-06-21 14:50:39 +02:00
.subcommand("withdrawManually", "withdraw-manually", {
help: "Withdraw manually from an exchange.",
})
.requiredOption("exchange", ["--exchange"], clk.STRING, {
help: "Base URL of the exchange.",
})
.requiredOption("amount", ["--amount"], clk.STRING, {
help: "Amount to withdraw",
})
.action(async (args) => {
await withWallet(args, async (wallet) => {
const exchange = await wallet.updateExchangeFromUrl(
args.withdrawManually.exchange,
);
const acct = exchange.wireInfo?.accounts[0];
if (!acct) {
console.log("exchange has no accounts");
return;
}
2020-07-16 19:22:56 +02:00
const reserve = await wallet.acceptManualWithdrawal(
exchange.baseUrl,
Amounts.parseOrThrow(args.withdrawManually.amount),
);
2020-06-21 14:50:39 +02:00
const completePaytoUri = addPaytoQueryParams(acct.payto_uri, {
amount: args.withdrawManually.amount,
message: `Taler top-up ${reserve.reservePub}`,
});
console.log("Created reserve", reserve.reservePub);
console.log("Payto URI", completePaytoUri);
2020-06-21 14:49:27 +02:00
});
});
const reservesCli = advancedCli.subcommand("reserves", "reserves", {
help: "Manage reserves.",
});
reservesCli
.subcommand("list", "list", {
help: "List reserves.",
})
.action(async (args) => {
await withWallet(args, async (wallet) => {
const reserves = await wallet.getReserves();
console.log(JSON.stringify(reserves, undefined, 2));
});
});
reservesCli
.subcommand("update", "update", {
help: "Update reserve status via exchange.",
})
.requiredArgument("reservePub", clk.STRING)
.action(async (args) => {
await withWallet(args, async (wallet) => {
await wallet.updateReserve(args.update.reservePub);
});
});
2019-11-30 00:36:20 +01:00
advancedCli
.subcommand("payPrepare", "pay-prepare", {
help: "Claim an order but don't pay yet.",
})
.requiredArgument("url", clk.STRING)
2020-03-24 10:55:04 +01:00
.action(async (args) => {
await withWallet(args, async (wallet) => {
2019-12-20 01:25:22 +01:00
const res = await wallet.preparePayForUri(args.payPrepare.url);
2019-11-30 00:36:20 +01:00
switch (res.status) {
case "error":
console.log("error:", res.error);
break;
case "insufficient-balance":
console.log("insufficient balance");
break;
case "paid":
console.log("already paid");
break;
case "payment-possible":
console.log("payment possible");
break;
default:
assertUnreachable(res);
}
});
});
2019-11-21 23:09:43 +01:00
advancedCli
.subcommand("refresh", "force-refresh", {
help: "Force a refresh on a coin.",
})
.requiredArgument("coinPub", clk.STRING)
2020-03-24 10:55:04 +01:00
.action(async (args) => {
await withWallet(args, async (wallet) => {
await wallet.refresh(args.refresh.coinPub);
2019-11-21 23:09:43 +01:00
});
});
2020-03-24 10:55:04 +01:00
advancedCli
.subcommand("dumpCoins", "dump-coins", {
help: "Dump coins in an easy-to-process format.",
})
.action(async (args) => {
await withWallet(args, async (wallet) => {
const coinDump = await wallet.dumpCoins();
console.log(JSON.stringify(coinDump, undefined, 2));
});
});
2020-03-27 19:48:25 +01:00
const coinPubListCodec = makeCodecForList(codecForString);
2020-03-24 10:55:04 +01:00
advancedCli
.subcommand("suspendCoins", "suspend-coins", {
help: "Mark a coin as suspended, will not be used for payments.",
})
.requiredArgument("coinPubSpec", clk.STRING)
.action(async (args) => {
await withWallet(args, async (wallet) => {
let coinPubList: string[];
try {
coinPubList = coinPubListCodec.decode(
JSON.parse(args.suspendCoins.coinPubSpec),
);
} catch (e) {
console.log("could not parse coin list:", e.message);
process.exit(1);
}
for (const c of coinPubList) {
await wallet.setCoinSuspended(c, true);
}
});
});
advancedCli
.subcommand("unsuspendCoins", "unsuspend-coins", {
help: "Mark a coin as suspended, will not be used for payments.",
})
.requiredArgument("coinPubSpec", clk.STRING)
.action(async (args) => {
await withWallet(args, async (wallet) => {
let coinPubList: string[];
try {
coinPubList = coinPubListCodec.decode(
JSON.parse(args.unsuspendCoins.coinPubSpec),
);
} catch (e) {
console.log("could not parse coin list:", e.message);
process.exit(1);
}
for (const c of coinPubList) {
await wallet.setCoinSuspended(c, false);
}
});
});
2019-11-21 23:09:43 +01:00
advancedCli
.subcommand("coins", "list-coins", {
help: "List coins.",
})
2020-03-24 10:55:04 +01:00
.action(async (args) => {
await withWallet(args, async (wallet) => {
2019-11-21 23:09:43 +01:00
const coins = await wallet.getCoins();
for (const coin of coins) {
console.log(`coin ${coin.coinPub}`);
console.log(` status ${coin.status}`);
console.log(` exchange ${coin.exchangeBaseUrl}`);
console.log(` denomPubHash ${coin.denomPubHash}`);
2019-11-30 00:36:20 +01:00
console.log(
` remaining amount ${Amounts.stringify(coin.currentAmount)}`,
2019-11-30 00:36:20 +01:00
);
2019-11-21 23:09:43 +01:00
}
});
});
advancedCli
.subcommand("updateReserve", "update-reserve", {
help: "Update reserve status.",
})
.requiredArgument("reservePub", clk.STRING)
2020-03-24 10:55:04 +01:00
.action(async (args) => {
await withWallet(args, async (wallet) => {
const r = await wallet.updateReserve(args.updateReserve.reservePub);
console.log("updated reserve:", JSON.stringify(r, undefined, 2));
});
});
advancedCli
.subcommand("updateReserve", "show-reserve", {
help: "Show the current reserve status.",
})
.requiredArgument("reservePub", clk.STRING)
2020-03-24 10:55:04 +01:00
.action(async (args) => {
await withWallet(args, async (wallet) => {
const r = await wallet.getReserve(args.updateReserve.reservePub);
console.log("updated reserve:", JSON.stringify(r, undefined, 2));
});
});
2019-11-21 23:09:43 +01:00
const testCli = walletCli.subcommand("testingArgs", "testing", {
help: "Subcommands for testing GNU Taler deployments.",
});
2020-06-21 14:50:39 +02:00
testCli.subcommand("vectors", "vectors").action(async (args) => {
const secretSeed = nacl.randomBytes(64);
const coinIndex = Math.ceil(Math.random() * 100);
const p = setupRefreshPlanchet(secretSeed, coinIndex);
console.log("setupRefreshPlanchet");
console.log(` (in) secret seed: ${encodeCrock(secretSeed)}`);
console.log(` (in) coin index: ${coinIndex}`);
console.log(` (out) blinding secret: ${encodeCrock(p.bks)}`);
console.log(` (out) coin priv: ${encodeCrock(p.coinPriv)}`);
console.log(` (out) coin pub: ${encodeCrock(p.coinPub)}`);
});
2020-06-08 16:02:38 +02:00
2020-03-23 12:30:01 +01:00
testCli
.subcommand("integrationtestBasic", "integrationtest-basic")
.requiredArgument("cfgfile", clk.STRING)
2020-03-24 10:55:04 +01:00
.action(async (args) => {
2020-03-23 12:30:01 +01:00
const cfgStr = fs.readFileSync(args.integrationtestBasic.cfgfile, "utf8");
const cfg = new Configuration();
cfg.loadFromString(cfgStr);
try {
await runIntegrationTestBasic(cfg);
} catch (e) {
console.log("integration test failed");
2020-03-24 10:55:04 +01:00
console.log(e);
2020-03-23 12:30:01 +01:00
process.exit(1);
}
process.exit(0);
});
2019-11-21 23:09:43 +01:00
testCli
2020-03-24 13:22:39 +01:00
.subcommand("testPayCmd", "test-pay", { help: "Create contract and pay." })
.requiredOption("merchant", ["-m", "--mechant-url"], clk.STRING)
.requiredOption("apikey", ["-k", "--mechant-api-key"], clk.STRING)
2019-11-21 23:09:43 +01:00
.requiredOption("amount", ["-a", "--amount"], clk.STRING)
2019-11-19 16:16:12 +01:00
.requiredOption("summary", ["-s", "--summary"], clk.STRING, {
default: "Test Payment",
})
2020-03-24 10:55:04 +01:00
.action(async (args) => {
2019-11-21 23:09:43 +01:00
const cmdArgs = args.testPayCmd;
2019-08-20 15:59:05 +02:00
console.log("creating order");
const merchantBackend = new MerchantBackendConnection(
2020-03-24 13:22:39 +01:00
args.testPayCmd.merchant,
args.testPayCmd.apikey,
);
const orderResp = await merchantBackend.createOrder(
2019-11-19 16:16:12 +01:00
cmdArgs.amount,
cmdArgs.summary,
"",
);
2019-08-20 15:59:05 +02:00
console.log("created new order with order ID", orderResp.orderId);
const checkPayResp = await merchantBackend.checkPayment(orderResp.orderId);
2019-08-28 02:49:27 +02:00
const talerPayUri = checkPayResp.taler_pay_uri;
if (!talerPayUri) {
console.error("fatal: no taler pay URI received from backend");
2019-08-20 15:59:05 +02:00
process.exit(1);
return;
}
2019-08-28 02:49:27 +02:00
console.log("taler pay URI:", talerPayUri);
2020-03-24 10:55:04 +01:00
await withWallet(args, async (wallet) => {
2019-11-21 23:09:43 +01:00
await doPay(wallet, talerPayUri, { alwaysYes: true });
});
2019-08-20 15:59:05 +02:00
});
2019-11-21 23:09:43 +01:00
testCli
2019-11-19 16:16:12 +01:00
.subcommand("integrationtestCmd", "integrationtest", {
help: "Run integration test with bank, exchange and merchant.",
})
.requiredOption("exchange", ["-e", "--exchange"], clk.STRING, {
default: "https://exchange.test.taler.net/",
})
.requiredOption("merchant", ["-m", "--merchant"], clk.STRING, {
default: "https://backend.test.taler.net/",
})
.requiredOption("merchantApiKey", ["-k", "--merchant-api-key"], clk.STRING, {
default: "sandbox",
})
.requiredOption("bank", ["-b", "--bank"], clk.STRING, {
default: "https://bank.test.taler.net/",
})
2020-02-24 18:40:36 +01:00
.requiredOption("withdrawAmount", ["-w", "--amount"], clk.STRING, {
2019-11-19 16:16:12 +01:00
default: "TESTKUDOS:10",
})
.requiredOption("spendAmount", ["-s", "--spend-amount"], clk.STRING, {
default: "TESTKUDOS:4",
})
2020-03-24 10:55:04 +01:00
.action(async (args) => {
2019-11-19 16:16:12 +01:00
applyVerbose(args.wallet.verbose);
2020-04-06 17:45:41 +02:00
const cmdObj = args.integrationtestCmd;
2019-11-19 16:16:12 +01:00
try {
await runIntegrationTest({
amountToSpend: cmdObj.spendAmount,
amountToWithdraw: cmdObj.withdrawAmount,
bankBaseUrl: cmdObj.bank,
exchangeBaseUrl: cmdObj.exchange,
merchantApiKey: cmdObj.merchantApiKey,
merchantBaseUrl: cmdObj.merchant,
2020-03-24 10:55:04 +01:00
}).catch((err) => {
2019-12-15 17:48:22 +01:00
console.error("Integration test failed with exception:");
2019-11-19 16:16:12 +01:00
console.error(err);
2020-01-17 22:00:58 +01:00
process.exit(1);
2019-11-19 16:16:12 +01:00
});
process.exit(0);
} catch (e) {
console.error(e);
process.exit(1);
}
});
2019-11-21 23:09:43 +01:00
testCli
2019-11-30 00:36:20 +01:00
.subcommand("genTipUri", "gen-tip-uri", {
help: "Generate a taler://tip URI.",
})
.requiredOption("amount", ["-a", "--amount"], clk.STRING, {
default: "TESTKUDOS:10",
})
.maybeOption("merchant", ["-m", "--merchant"], clk.STRING, {
default: "https://backend.test.taler.net/",
})
.maybeOption("merchantApiKey", ["-k", "--merchant-api-key"], clk.STRING, {
default: "sandbox",
})
2020-03-24 10:55:04 +01:00
.action(async (args) => {
2019-11-30 00:36:20 +01:00
const merchantBackend = new MerchantBackendConnection(
args.genTipUri.merchant ?? "https://backend.test.taler.net/",
args.genTipUri.merchantApiKey ?? "sandbox",
2019-11-30 00:36:20 +01:00
);
const tipUri = await merchantBackend.authorizeTip(
args.genTipUri.amount,
"test",
);
2019-11-30 00:36:20 +01:00
console.log(tipUri);
});
2019-12-06 00:56:31 +01:00
testCli
.subcommand("genWithdrawUri", "gen-withdraw-uri", {
help: "Generate a taler://withdraw URI.",
})
.requiredOption("amount", ["-a", "--amount"], clk.STRING, {
default: "TESTKUDOS:20",
})
.requiredOption("bank", ["-b", "--bank"], clk.STRING, {
default: "https://bank.test.taler.net/",
})
2020-03-24 10:55:04 +01:00
.action(async (args) => {
2019-12-06 00:56:31 +01:00
const b = new Bank(args.genWithdrawUri.bank);
const user = await b.registerRandomUser();
const url = await b.generateWithdrawUri(user, args.genWithdrawUri.amount);
console.log(url);
});
2019-11-30 00:36:20 +01:00
testCli
.subcommand("genRefundUri", "gen-refund-uri", {
help: "Generate a taler://refund URI.",
})
.requiredOption("amount", ["-a", "--amount"], clk.STRING, {
default: "TESTKUDOS:5",
})
.requiredOption("refundAmount", ["-r", "--refund"], clk.STRING, {
default: "TESTKUDOS:3",
})
.requiredOption("summary", ["-s", "--summary"], clk.STRING, {
default: "Test Payment (for refund)",
})
.maybeOption("merchant", ["-m", "--merchant"], clk.STRING, {
default: "https://backend.test.taler.net/",
})
.maybeOption("merchantApiKey", ["-k", "--merchant-api-key"], clk.STRING, {
default: "sandbox",
})
2020-03-24 10:55:04 +01:00
.action(async (args) => {
2019-11-30 00:36:20 +01:00
const cmdArgs = args.genRefundUri;
const merchantBackend = new MerchantBackendConnection(
cmdArgs.merchant ?? "https://backend.test.taler.net/",
cmdArgs.merchantApiKey ?? "sandbox",
2019-11-30 00:36:20 +01:00
);
const orderResp = await merchantBackend.createOrder(
cmdArgs.amount,
cmdArgs.summary,
"",
);
console.log("created new order with order ID", orderResp.orderId);
const checkPayResp = await merchantBackend.checkPayment(orderResp.orderId);
const talerPayUri = checkPayResp.taler_pay_uri;
if (!talerPayUri) {
console.error("fatal: no taler pay URI received from backend");
process.exit(1);
return;
}
2020-03-24 10:55:04 +01:00
await withWallet(args, async (wallet) => {
2019-11-30 00:36:20 +01:00
await doPay(wallet, talerPayUri, { alwaysYes: true });
});
const refundUri = await merchantBackend.refund(
orderResp.orderId,
"test refund",
cmdArgs.refundAmount,
);
console.log(refundUri);
});
testCli
.subcommand("genPayUri", "gen-pay-uri", {
help: "Generate a taler://pay URI.",
})
.flag("qrcode", ["--qr"], {
help: "Show a QR code with the taler://pay URI",
})
.flag("wait", ["--wait"], {
help: "Wait until payment has completed",
})
2019-11-21 23:09:43 +01:00
.requiredOption("amount", ["-a", "--amount"], clk.STRING, {
default: "TESTKUDOS:1",
})
.requiredOption("summary", ["-s", "--summary"], clk.STRING, {
default: "Test Payment",
})
2019-12-25 19:11:20 +01:00
.requiredOption("merchant", ["-m", "--merchant"], clk.STRING, {
default: "https://backend.test.taler.net/",
})
.requiredOption("merchantApiKey", ["-k", "--merchant-api-key"], clk.STRING, {
default: "sandbox",
})
2020-03-24 10:55:04 +01:00
.action(async (args) => {
2019-11-30 00:36:20 +01:00
const cmdArgs = args.genPayUri;
2019-11-21 23:09:43 +01:00
console.log("creating order");
const merchantBackend = new MerchantBackendConnection(
2019-12-25 19:11:20 +01:00
cmdArgs.merchant,
cmdArgs.merchantApiKey,
2019-11-21 23:09:43 +01:00
);
const orderResp = await merchantBackend.createOrder(
cmdArgs.amount,
cmdArgs.summary,
"",
);
console.log("created new order with order ID", orderResp.orderId);
const checkPayResp = await merchantBackend.checkPayment(orderResp.orderId);
const talerPayUri = checkPayResp.taler_pay_uri;
if (!talerPayUri) {
console.error("fatal: no taler pay URI received from backend");
2019-08-28 02:49:27 +02:00
process.exit(1);
return;
}
2019-11-21 23:09:43 +01:00
console.log("taler pay URI:", talerPayUri);
2019-11-30 00:36:20 +01:00
if (cmdArgs.qrcode) {
const qrcode = qrcodeGenerator(0, "M");
qrcode.addData(talerPayUri);
qrcode.make();
console.log(qrcode.createASCII());
}
if (cmdArgs.wait) {
console.log("waiting for payment ...");
while (1) {
await asyncSleep(500);
const checkPayResp2 = await merchantBackend.checkPayment(
orderResp.orderId,
);
if (checkPayResp2.paid) {
console.log("payment successfully received!");
break;
}
2019-11-21 23:09:43 +01:00
}
2019-08-28 02:49:27 +02:00
}
2019-08-30 17:27:59 +02:00
});
2019-11-19 16:16:12 +01:00
testCli
.subcommand("withdrawArgs", "withdraw", {
help: "Withdraw from a test bank (must support test registrations).",
})
2019-11-21 23:09:43 +01:00
.requiredOption("amount", ["-a", "--amount"], clk.STRING, {
default: "TESTKUDOS:10",
help: "Amount to withdraw.",
})
2019-11-19 16:16:12 +01:00
.requiredOption("exchange", ["-e", "--exchange"], clk.STRING, {
default: "https://exchange.test.taler.net/",
help: "Exchange base URL.",
})
.requiredOption("bank", ["-b", "--bank"], clk.STRING, {
default: "https://bank.test.taler.net/",
help: "Bank base URL",
})
2020-03-24 10:55:04 +01:00
.action(async (args) => {
await withWallet(args, async (wallet) => {
2020-07-16 17:21:22 +02:00
await wallet.updateExchangeFromUrl(args.withdrawArgs.exchange, true);
2019-11-21 23:09:43 +01:00
await withdrawTestBalance(
wallet,
args.withdrawArgs.amount,
args.withdrawArgs.bank,
args.withdrawArgs.exchange,
);
logger.info("Withdraw done");
2019-11-19 16:16:12 +01:00
});
});
2019-11-19 16:16:12 +01:00
walletCli.run();