aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/TalerErrorCode.ts3100
-rw-r--r--src/android/index.ts287
-rw-r--r--src/crypto/primitives/kdf.ts92
-rw-r--r--src/crypto/primitives/nacl-fast.ts1941
-rw-r--r--src/crypto/primitives/sha256.ts426
-rw-r--r--src/crypto/talerCrypto-test.ts197
-rw-r--r--src/crypto/talerCrypto.ts376
-rw-r--r--src/crypto/workers/browserWorkerEntry.ts74
-rw-r--r--src/crypto/workers/cryptoApi.ts467
-rw-r--r--src/crypto/workers/cryptoImplementation.ts581
-rw-r--r--src/crypto/workers/cryptoWorker.ts8
-rw-r--r--src/crypto/workers/nodeThreadWorker.ts183
-rw-r--r--src/crypto/workers/synchronousWorker.ts137
-rw-r--r--src/db.ts65
-rw-r--r--src/headless/NodeHttpLib.ts133
-rw-r--r--src/headless/clk.ts614
-rw-r--r--src/headless/helpers.ts134
-rw-r--r--src/headless/taler-wallet-cli.ts658
-rw-r--r--src/i18n/de.po363
-rw-r--r--src/i18n/en-US.po294
-rw-r--r--src/i18n/fr.po290
-rw-r--r--src/i18n/it.po290
-rw-r--r--src/i18n/poheader26
-rw-r--r--src/i18n/strings-prelude17
-rw-r--r--src/i18n/strings.ts373
-rw-r--r--src/i18n/sv.po388
-rw-r--r--src/i18n/taler-wallet-webex.pot290
-rw-r--r--src/index.ts22
-rw-r--r--src/operations/balance.ts153
-rw-r--r--src/operations/errors.ts121
-rw-r--r--src/operations/exchanges.ts554
-rw-r--r--src/operations/pay.ts1147
-rw-r--r--src/operations/pending.ts458
-rw-r--r--src/operations/recoup.ts411
-rw-r--r--src/operations/refresh.ts572
-rw-r--r--src/operations/refund.ts425
-rw-r--r--src/operations/reserves.ts840
-rw-r--r--src/operations/state.ts65
-rw-r--r--src/operations/tip.ts342
-rw-r--r--src/operations/transactions.ts292
-rw-r--r--src/operations/versions.ts38
-rw-r--r--src/operations/withdraw-test.ts332
-rw-r--r--src/operations/withdraw.ts756
-rw-r--r--src/types/ReserveStatus.ts57
-rw-r--r--src/types/ReserveTransaction.ts250
-rw-r--r--src/types/dbTypes.ts1818
-rw-r--r--src/types/notifications.ts255
-rw-r--r--src/types/pending.ts258
-rw-r--r--src/types/schemacore.ts58
-rw-r--r--src/types/talerTypes.ts1271
-rw-r--r--src/types/transactions.ts310
-rw-r--r--src/types/types-test.ts55
-rw-r--r--src/types/walletTypes.ts522
-rw-r--r--src/util/RequestThrottler.ts128
-rw-r--r--src/util/amounts-test.ts140
-rw-r--r--src/util/amounts.ts383
-rw-r--r--src/util/assertUnreachable.ts19
-rw-r--r--src/util/asyncMemo.ts87
-rw-r--r--src/util/codec-test.ts78
-rw-r--r--src/util/codec.ts410
-rw-r--r--src/util/helpers-test.ts46
-rw-r--r--src/util/helpers.ts147
-rw-r--r--src/util/http.ts362
-rw-r--r--src/util/libtoolVersion-test.ts48
-rw-r--r--src/util/libtoolVersion.ts88
-rw-r--r--src/util/logging.ts87
-rw-r--r--src/util/payto-test.ts31
-rw-r--r--src/util/payto.ts69
-rw-r--r--src/util/promiseUtils.ts60
-rw-r--r--src/util/query.ts575
-rw-r--r--src/util/reserveHistoryUtil-test.ts285
-rw-r--r--src/util/reserveHistoryUtil.ts360
-rw-r--r--src/util/talerconfig.ts120
-rw-r--r--src/util/taleruri-test.ts193
-rw-r--r--src/util/taleruri.ts211
-rw-r--r--src/util/time.ts198
-rw-r--r--src/util/timer.ts160
-rw-r--r--src/util/wire.ts51
-rw-r--r--src/wallet-test.ts121
-rw-r--r--src/wallet.ts881
-rw-r--r--src/walletCoreApiHandler.ts325
-rw-r--r--src/webex/background.ts30
-rw-r--r--src/webex/chromeBadge.ts288
-rw-r--r--src/webex/compat.ts85
-rw-r--r--src/webex/i18n-test.tsx69
-rw-r--r--src/webex/i18n.tsx250
-rw-r--r--src/webex/pageEntryPoint.ts72
-rw-r--r--src/webex/pages/add-auditor.tsx135
-rw-r--r--src/webex/pages/auditors.tsx161
-rw-r--r--src/webex/pages/benchmark.tsx104
-rw-r--r--src/webex/pages/pay.tsx182
-rw-r--r--src/webex/pages/payback.tsx30
-rw-r--r--src/webex/pages/popup.tsx499
-rw-r--r--src/webex/pages/refund.tsx89
-rw-r--r--src/webex/pages/reset-required.tsx93
-rw-r--r--src/webex/pages/return-coins.tsx30
-rw-r--r--src/webex/pages/tip.tsx103
-rw-r--r--src/webex/pages/welcome.tsx190
-rw-r--r--src/webex/pages/withdraw.tsx229
-rw-r--r--src/webex/permissions.ts20
-rw-r--r--src/webex/renderHtml.tsx344
-rw-r--r--src/webex/wxApi.ts310
-rw-r--r--src/webex/wxBackend.ts575
103 files changed, 0 insertions, 32737 deletions
diff --git a/src/TalerErrorCode.ts b/src/TalerErrorCode.ts
deleted file mode 100644
index 56c28ee20..000000000
--- a/src/TalerErrorCode.ts
+++ /dev/null
@@ -1,3100 +0,0 @@
-/*
- This file is part of GNU Taler
- Copyright (C) 2012-2020 Taler Systems SA
-
- GNU Taler is free software: you can redistribute it and/or modify it
- under the terms of the GNU Lesser General Public License as published
- by the Free Software Foundation, either version 3 of the License,
- 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
-
- SPDX-License-Identifier: LGPL3.0-or-later
-
- Note: the LGPL does not apply to all components of GNU Taler,
- but it does apply to this file.
- */
-
-export enum TalerErrorCode {
-
-
- /**
- * Special code to indicate no error (or no "code" present).
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- NONE = 0,
-
- /**
- * Special code to indicate that a non-integer error code was returned in the JSON response.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- INVALID = 1,
-
- /**
- * The response we got from the server was not even in JSON format.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- INVALID_RESPONSE = 2,
-
- /**
- * Generic implementation error: this function was not yet implemented.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- NOT_IMPLEMENTED = 3,
-
- /**
- * Exchange is badly configured and thus cannot operate.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- EXCHANGE_BAD_CONFIGURATION = 4,
-
- /**
- * Internal assertion error.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- INTERNAL_INVARIANT_FAILURE = 5,
-
- /**
- * Operation timed out.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIMEOUT = 6,
-
- /**
- * Exchange failed to allocate memory for building JSON reply.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- JSON_ALLOCATION_FAILURE = 7,
-
- /**
- * HTTP method invalid for this URL.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- METHOD_INVALID = 8,
-
- /**
- * Operation specified invalid for this URL (resulting in a "NOT FOUND" for the overall response).
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- OPERATION_INVALID = 9,
-
- /**
- * There is no endpoint defined for the URL provided by the client.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ENDPOINT_UNKNOWN = 10,
-
- /**
- * The URI is longer than the longest URI the HTTP server is willing to parse.
- * Returned with an HTTP status code of #MHD_HTTP_URI_TOO_LONG (414).
- * (A value of 0 indicates that the error is generated client-side).
- */
- URI_TOO_LONG = 11,
-
- /**
- * The number of segments included in the URI does not match the number of segments expected by the endpoint.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WRONG_NUMBER_OF_SEGMENTS = 12,
-
- /**
- * The start and end-times in the wire fee structure leave a hole. This is not allowed. Generated as an error on the client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- HOLE_IN_WIRE_FEE_STRUCTURE = 13,
-
- /**
- * The version string given does not follow the expected CURRENT:REVISION:AGE Format. Generated as an error on the client side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- VERSION_MALFORMED = 14,
-
- /**
- * The client-side experienced an internal failure. Generated as an error on the client side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- CLIENT_INTERNAL_FAILURE = 15,
-
- /**
- * The body is too large to be permissible for the endpoint.
- * Returned with an HTTP status code of #MHD_HTTP_PAYLOAD_TOO_LARGE (413).
- * (A value of 0 indicates that the error is generated client-side).
- */
- UPLOAD_EXCEEDS_LIMIT = 16,
-
- /**
- * The payto:// URI we got is malformed.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAYTO_MALFORMED = 17,
-
- /**
- * The exchange failed to even just initialize its connection to the database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DB_SETUP_FAILED = 1001,
-
- /**
- * The exchange encountered an error event to just start the database transaction.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DB_START_FAILED = 1002,
-
- /**
- * The exchange encountered an error event to commit the database transaction (hard, unrecoverable error).
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DB_COMMIT_FAILED_HARD = 1003,
-
- /**
- * The exchange encountered an error event to commit the database transaction, even after repeatedly retrying it there was always a conflicting transaction. (This indicates a repeated serialization error; should only happen if some client maliciously tries to create conflicting concurrent transactions.)
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DB_COMMIT_FAILED_ON_RETRY = 1004,
-
- /**
- * The exchange had insufficient memory to parse the request.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PARSER_OUT_OF_MEMORY = 1005,
-
- /**
- * The JSON in the client's request to the exchange was malformed. (Generic parse error).
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- JSON_INVALID = 1006,
-
- /**
- * The JSON in the client's request to the exchange was malformed. Details about the location of the parse error are provided.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- JSON_INVALID_WITH_DETAILS = 1007,
-
- /**
- * A required parameter in the request to the exchange was missing.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PARAMETER_MISSING = 1008,
-
- /**
- * A parameter in the request to the exchange was malformed.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PARAMETER_MALFORMED = 1009,
-
- /**
- * The exchange failed to obtain the transaction history of the given coin from the database while generating an insufficient funds errors. This can happen during /deposit or /recoup requests.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- COIN_HISTORY_DB_ERROR_INSUFFICIENT_FUNDS = 1010,
-
- /**
- * Internal logic error. Some server-side function failed that really should not.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- INTERNAL_LOGIC_ERROR = 1011,
-
- /**
- * The method specified in a payto:// URI is not one we expected.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAYTO_WRONG_METHOD = 1012,
-
- /**
- * The same coin was already used with a different denomination previously.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- COIN_CONFLICTING_DENOMINATION_KEY = 1013,
-
- /**
- * We failed to update the database of known coins.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DB_COIN_HISTORY_STORE_ERROR = 1014,
-
- /**
- * The public key of given to a /coins/ handler was malformed.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- COINS_INVALID_COIN_PUB = 1050,
-
- /**
- * The reserve key of given to a /reserves/ handler was malformed.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RESERVES_INVALID_RESERVE_PUB = 1051,
-
- /**
- * The public key of given to a /transfers/ handler was malformed.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TRANSFERS_INVALID_WTID = 1052,
-
- /**
- * The wire hash of given to a /deposits/ handler was malformed.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSITS_INVALID_H_WIRE = 1053,
-
- /**
- * The merchant key of given to a /deposits/ handler was malformed.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSITS_INVALID_MERCHANT_PUB = 1054,
-
- /**
- * The hash of the contract terms given to a /deposits/ handler was malformed.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSITS_INVALID_H_CONTRACT_TERMS = 1055,
-
- /**
- * The coin public key of given to a /deposits/ handler was malformed.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSITS_INVALID_COIN_PUB = 1056,
-
- /**
- * The body returned by the exchange for a /deposits/ request was malformed. Error created client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSITS_INVALID_BODY_BY_EXCHANGE = 1057,
-
- /**
- * The signature returned by the exchange in a /deposits/ request was malformed. Error created client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSITS_INVALID_SIGNATURE_BY_EXCHANGE = 1058,
-
- /**
- * The given reserve does not have sufficient funds to admit the requested withdraw operation at this time. The response includes the current "balance" of the reserve as well as the transaction "history" that lead to this balance.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WITHDRAW_INSUFFICIENT_FUNDS = 1100,
-
- /**
- * The exchange has no information about the "reserve_pub" that was given.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WITHDRAW_RESERVE_UNKNOWN = 1101,
-
- /**
- * The amount to withdraw together with the fee exceeds the numeric range for Taler amounts. This is not a client failure, as the coin value and fees come from the exchange's configuration.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WITHDRAW_AMOUNT_FEE_OVERFLOW = 1102,
-
- /**
- * All of the deposited amounts into this reserve total up to a value that is too big for the numeric range for Taler amounts. This is not a client failure, as the transaction history comes from the exchange's configuration.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- AMOUNT_DEPOSITS_OVERFLOW = 1103,
-
- /**
- * For one of the historic withdrawals from this reserve, the exchange could not find the denomination key. This is not a client failure, as the transaction history comes from the exchange's configuration.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WITHDRAW_HISTORIC_DENOMINATION_KEY_NOT_FOUND = 1104,
-
- /**
- * All of the withdrawals from reserve total up to a value that is too big for the numeric range for Taler amounts. This is not a client failure, as the transaction history comes from the exchange's configuration.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WITHDRAW_AMOUNT_WITHDRAWALS_OVERFLOW = 1105,
-
- /**
- * The exchange somehow knows about this reserve, but there seem to have been no wire transfers made. This is not a client failure, as this is a database consistency issue of the exchange.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WITHDRAW_RESERVE_WITHOUT_WIRE_TRANSFER = 1106,
-
- /**
- * The exchange failed to create the signature using the denomination key.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WITHDRAW_SIGNATURE_FAILED = 1107,
-
- /**
- * The exchange failed to store the withdraw operation in its database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WITHDRAW_DB_STORE_ERROR = 1108,
-
- /**
- * The exchange failed to check against historic withdraw data from database (as part of ensuring the idempotency of the operation).
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WITHDRAW_DB_FETCH_ERROR = 1109,
-
- /**
- * The exchange is not aware of the denomination key the wallet requested for the withdrawal.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WITHDRAW_DENOMINATION_KEY_NOT_FOUND = 1110,
-
- /**
- * The signature of the reserve is not valid.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WITHDRAW_RESERVE_SIGNATURE_INVALID = 1111,
-
- /**
- * When computing the reserve history, we ended up with a negative overall balance, which should be impossible.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WITHDRAW_HISTORY_DB_ERROR_INSUFFICIENT_FUNDS = 1112,
-
- /**
- * When computing the reserve history, we ended up with a negative overall balance, which should be impossible.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WITHDRAW_RESERVE_HISTORY_IMPOSSIBLE = 1113,
-
- /**
- * Validity period of the coin to be withdrawn is in the future.
- * Returned with an HTTP status code of #MHD_HTTP_PRECONDITION_FAILED (412).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WITHDRAW_VALIDITY_IN_FUTURE = 1114,
-
- /**
- * Withdraw period of the coin to be withdrawn is in the past.
- * Returned with an HTTP status code of #MHD_HTTP_GONE (410).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WITHDRAW_VALIDITY_IN_PAST = 1115,
-
- /**
- * Withdraw period of the coin to be withdrawn is in the past.
- * Returned with an HTTP status code of #MHD_HTTP_GONE (410).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DENOMINATION_KEY_LOST = 1116,
-
- /**
- * The exchange's database entry with the reserve balance summary is inconsistent with its own history of the reserve.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WITHDRAW_RESERVE_BALANCE_CORRUPT = 1117,
-
- /**
- * The exchange responded with a reply that did not satsify the protocol. This error is not used in the protocol but created client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WITHDRAW_REPLY_MALFORMED = 1118,
-
- /**
- * The client failed to unblind the blind signature. This error is not used in the protocol but created client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WITHDRAW_UNBLIND_FAILURE = 1119,
-
- /**
- * The exchange failed to obtain the transaction history of the given reserve from the database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RESERVE_STATUS_DB_ERROR = 1150,
-
- /**
- * The reserve status was requested using a unknown key, to be returned with 404 Not Found.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RESERVE_STATUS_UNKNOWN = 1151,
-
- /**
- * The exchange responded with a reply that did not satsify the protocol. This error is not used in the protocol but created client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RESERVE_STATUS_REPLY_MALFORMED = 1152,
-
- /**
- * The respective coin did not have sufficient residual value for the /deposit operation (i.e. due to double spending). The "history" in the response provides the transaction history of the coin proving this fact.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_INSUFFICIENT_FUNDS = 1200,
-
- /**
- * The exchange failed to obtain the transaction history of the given coin from the database (this does not happen merely because the coin is seen by the exchange for the first time).
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_HISTORY_DB_ERROR = 1201,
-
- /**
- * The exchange failed to store the /depost information in the database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_STORE_DB_ERROR = 1202,
-
- /**
- * The exchange database is unaware of the denomination key that signed the coin (however, the exchange process is; this is not supposed to happen; it can happen if someone decides to purge the DB behind the back of the exchange process). Hence the deposit is being refused.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_DB_DENOMINATION_KEY_UNKNOWN = 1203,
-
- /**
- * The exchange was trying to lookup the denomination key for the purpose of a DEPOSIT operation. However, the denomination key is unavailable for that purpose. This can be because it is entirely unknown to the exchange or not in the validity period for the deposit operation. Hence the deposit is being refused.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_DENOMINATION_KEY_UNKNOWN = 1204,
-
- /**
- * The signature made by the coin over the deposit permission is not valid.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_COIN_SIGNATURE_INVALID = 1205,
-
- /**
- * The signature of the denomination key over the coin is not valid.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_DENOMINATION_SIGNATURE_INVALID = 1206,
-
- /**
- * The stated value of the coin after the deposit fee is subtracted would be negative.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_NEGATIVE_VALUE_AFTER_FEE = 1207,
-
- /**
- * The stated refund deadline is after the wire deadline.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_REFUND_DEADLINE_AFTER_WIRE_DEADLINE = 1208,
-
- /**
- * The exchange does not recognize the validity of or support the given wire format type.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_INVALID_WIRE_FORMAT_TYPE = 1209,
-
- /**
- * The exchange failed to canonicalize and hash the given wire format. For example, the merchant failed to provide the "salt" or a valid payto:// URI in the wire details. Note that while the exchange will do some basic sanity checking on the wire details, it cannot warrant that the banking system will ultimately be able to route to the specified address, even if this check passed.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_INVALID_WIRE_FORMAT_JSON = 1210,
-
- /**
- * The hash of the given wire address does not match the wire hash specified in the proposal data.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_INVALID_WIRE_FORMAT_CONTRACT_HASH_CONFLICT = 1211,
-
- /**
- * The exchange detected that the given account number is invalid for the selected wire format type.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_INVALID_WIRE_FORMAT_ACCOUNT_NUMBER = 1213,
-
- /**
- * Timestamp included in deposit permission is intolerably far off with respect to the clock of the exchange.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_INVALID_TIMESTAMP = 1218,
-
- /**
- * Validity period of the denomination key is in the future.
- * Returned with an HTTP status code of #MHD_HTTP_PRECONDITION_FAILED (412).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_DENOMINATION_VALIDITY_IN_FUTURE = 1219,
-
- /**
- * Denomination key of the coin is past the deposit deadline.
- * Returned with an HTTP status code of #MHD_HTTP_GONE (410).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_DENOMINATION_EXPIRED = 1220,
-
- /**
- * The signature provided by the exchange is not valid. Error created client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_INVALID_SIGNATURE_BY_EXCHANGE = 1221,
-
- /**
- * The currency specified for the deposit is different from the currency of the coin.
- * Returned with an HTTP status code of #MHD_HTTP_PRECONDITION_FAILED (412).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_CURRENCY_MISMATCH = 1222,
-
- /**
- * The respective coin did not have sufficient residual value for the /refresh/melt operation. The "history" in this response provdes the "residual_value" of the coin, which may be less than its "original_value".
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- MELT_INSUFFICIENT_FUNDS = 1300,
-
- /**
- * The respective coin did not have sufficient residual value for the /refresh/melt operation. The "history" in this response provdes the "residual_value" of the coin, which may be less than its "original_value".
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- MELT_DENOMINATION_KEY_NOT_FOUND = 1301,
-
- /**
- * The exchange had an internal error reconstructing the transaction history of the coin that was being melted.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- MELT_COIN_HISTORY_COMPUTATION_FAILED = 1302,
-
- /**
- * The exchange failed to check against historic melt data from database (as part of ensuring the idempotency of the operation).
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- MELT_DB_FETCH_ERROR = 1303,
-
- /**
- * The exchange failed to store session data in the database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- MELT_DB_STORE_SESSION_ERROR = 1304,
-
- /**
- * The exchange encountered melt fees exceeding the melted coin's contribution.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- MELT_FEES_EXCEED_CONTRIBUTION = 1305,
-
- /**
- * The denomination key signature on the melted coin is invalid.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- MELT_DENOMINATION_SIGNATURE_INVALID = 1306,
-
- /**
- * The signature made with the coin to be melted is invalid.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- MELT_COIN_SIGNATURE_INVALID = 1307,
-
- /**
- * The exchange failed to obtain the transaction history of the given coin from the database while generating an insufficient funds errors.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- MELT_HISTORY_DB_ERROR_INSUFFICIENT_FUNDS = 1308,
-
- /**
- * The denomination of the given coin has past its expiration date and it is also not a valid zombie (that is, was not refreshed with the fresh coin being subjected to recoup).
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- MELT_COIN_EXPIRED_NO_ZOMBIE = 1309,
-
- /**
- * The signature returned by the exchange in a melt request was malformed. Error created client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- MELT_INVALID_SIGNATURE_BY_EXCHANGE = 1310,
-
- /**
- * The currency specified for the melt amount is different from the currency of the coin.
- * Returned with an HTTP status code of #MHD_HTTP_PRECONDITION_FAILED (412).
- * (A value of 0 indicates that the error is generated client-side).
- */
- MELT_CURRENCY_MISMATCH = 1311,
-
- /**
- * The exchange is unaware of the denomination key that was used to sign the melted zombie coin.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFRESH_RECOUP_DENOMINATION_KEY_NOT_FOUND = 1351,
-
- /**
- * Validity period of the denomination key is in the future.
- * Returned with an HTTP status code of #MHD_HTTP_PRECONDITION_FAILED (412).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFRESH_RECOUP_DENOMINATION_VALIDITY_IN_FUTURE = 1352,
-
- /**
- * Denomination key of the coin is past the deposit deadline.
- * Returned with an HTTP status code of #MHD_HTTP_GONE (410).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFRESH_RECOUP_DENOMINATION_EXPIRED = 1353,
-
- /**
- * Denomination key of the coin is past the deposit deadline.
- * Returned with an HTTP status code of #MHD_HTTP_GONE (410).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFRESH_ZOMBIE_DENOMINATION_EXPIRED = 1354,
-
- /**
- * The provided transfer keys do not match up with the original commitment. Information about the original commitment is included in the response.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REVEAL_COMMITMENT_VIOLATION = 1370,
-
- /**
- * Failed to produce the blinded signatures over the coins to be returned.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REVEAL_SIGNING_ERROR = 1371,
-
- /**
- * The exchange is unaware of the refresh session specified in the request.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REVEAL_SESSION_UNKNOWN = 1372,
-
- /**
- * The exchange failed to retrieve valid session data from the database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REVEAL_DB_FETCH_SESSION_ERROR = 1373,
-
- /**
- * The exchange failed to retrieve previously revealed data from the database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REVEAL_DB_FETCH_REVEAL_ERROR = 1374,
-
- /**
- * The exchange failed to retrieve commitment data from the database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REVEAL_DB_COMMIT_ERROR = 1375,
-
- /**
- * The size of the cut-and-choose dimension of the private transfer keys request does not match #TALER_CNC_KAPPA - 1.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REVEAL_CNC_TRANSFER_ARRAY_SIZE_INVALID = 1376,
-
- /**
- * The number of coins to be created in refresh exceeds the limits of the exchange. private transfer keys request does not match #TALER_CNC_KAPPA - 1.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REVEAL_NEW_DENOMS_ARRAY_SIZE_EXCESSIVE = 1377,
-
- /**
- * The number of envelopes given does not match the number of denomination keys given.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REVEAL_NEW_DENOMS_ARRAY_SIZE_MISMATCH = 1378,
-
- /**
- * The exchange encountered a numeric overflow totaling up the cost for the refresh operation.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REVEAL_COST_CALCULATION_OVERFLOW = 1379,
-
- /**
- * The exchange's cost calculation shows that the melt amount is below the costs of the transaction.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REVEAL_AMOUNT_INSUFFICIENT = 1380,
-
- /**
- * The exchange is unaware of the denomination key that was requested for one of the fresh coins.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REVEAL_FRESH_DENOMINATION_KEY_NOT_FOUND = 1381,
-
- /**
- * The signature made with the coin over the link data is invalid.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REVEAL_LINK_SIGNATURE_INVALID = 1382,
-
- /**
- * The exchange failed to generate the signature as it could not find the signing key for the denomination.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REVEAL_KEYS_MISSING = 1383,
-
- /**
- * The refresh session hash given to a /refreshes/ handler was malformed.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REVEAL_INVALID_RCH = 1384,
-
- /**
- * The exchange responded with a reply that did not satsify the protocol. This error is not used in the protocol but created client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REVEAL_REPLY_MALFORMED = 1385,
-
- /**
- * The coin specified in the link request is unknown to the exchange.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- LINK_COIN_UNKNOWN = 1400,
-
- /**
- * The exchange responded with a reply that did not satsify the protocol. This error is not used in the protocol but created client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- LINK_REPLY_MALFORMED = 1401,
-
- /**
- * The exchange knows literally nothing about the coin we were asked to refund. But without a transaction history, we cannot issue a refund. This is kind-of OK, the owner should just refresh it directly without executing the refund.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_COIN_NOT_FOUND = 1500,
-
- /**
- * We could not process the refund request as the coin's transaction history does not permit the requested refund at this time. The "history" in the response proves this.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_CONFLICT = 1501,
-
- /**
- * The exchange knows about the coin we were asked to refund, but not about the specific /deposit operation. Hence, we cannot issue a refund (as we do not know if this merchant public key is authorized to do a refund).
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_DEPOSIT_NOT_FOUND = 1503,
-
- /**
- * The currency specified for the refund is different from the currency of the coin.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_CURRENCY_MISMATCH = 1504,
-
- /**
- * When we tried to check if we already paid out the coin, the exchange's database suddenly disagreed with data it previously provided (internal inconsistency).
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_DB_INCONSISTENT = 1505,
-
- /**
- * The exchange can no longer refund the customer/coin as the money was already transferred (paid out) to the merchant. (It should be past the refund deadline.)
- * Returned with an HTTP status code of #MHD_HTTP_GONE (410).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_MERCHANT_ALREADY_PAID = 1506,
-
- /**
- * The amount the exchange was asked to refund exceeds (with fees) the total amount of the deposit (including fees).
- * Returned with an HTTP status code of #MHD_HTTP_PRECONDITION_FAILED (412).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_INSUFFICIENT_FUNDS = 1507,
-
- /**
- * The exchange failed to recover information about the denomination key of the refunded coin (even though it recognizes the key). Hence it could not check the fee structure.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_DENOMINATION_KEY_NOT_FOUND = 1508,
-
- /**
- * The refund fee specified for the request is lower than the refund fee charged by the exchange for the given denomination key of the refunded coin.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_FEE_TOO_LOW = 1509,
-
- /**
- * The exchange failed to store the refund information to its database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_STORE_DB_ERROR = 1510,
-
- /**
- * The refund fee is specified in a different currency than the refund amount.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_FEE_CURRENCY_MISMATCH = 1511,
-
- /**
- * The refunded amount is smaller than the refund fee, which would result in a negative refund.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_FEE_ABOVE_AMOUNT = 1512,
-
- /**
- * The signature of the merchant is invalid.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_MERCHANT_SIGNATURE_INVALID = 1513,
-
- /**
- * Merchant backend failed to create the refund confirmation signature.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_MERCHANT_SIGNING_FAILED = 1514,
-
- /**
- * The signature returned by the exchange in a refund request was malformed. Error created client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_INVALID_SIGNATURE_BY_EXCHANGE = 1515,
-
- /**
- * The wire format specified in the "sender_account_details" is not understood or not supported by this exchange.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ADMIN_ADD_INCOMING_WIREFORMAT_UNSUPPORTED = 1600,
-
- /**
- * The currency specified in the "amount" parameter is not supported by this exhange.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ADMIN_ADD_INCOMING_CURRENCY_UNSUPPORTED = 1601,
-
- /**
- * The exchange failed to store information about the incoming transfer in its database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ADMIN_ADD_INCOMING_DB_STORE = 1602,
-
- /**
- * The exchange encountered an error (that is not about not finding the wire transfer) trying to lookup a wire transfer identifier in the database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TRANSFERS_GET_DB_FETCH_FAILED = 1700,
-
- /**
- * The exchange found internally inconsistent data when resolving a wire transfer identifier in the database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TRANSFERS_GET_DB_INCONSISTENT = 1701,
-
- /**
- * The exchange did not find information about the specified wire transfer identifier in the database.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TRANSFERS_GET_WTID_NOT_FOUND = 1702,
-
- /**
- * The exchange did not find information about the wire transfer fees it charged.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TRANSFERS_GET_WIRE_FEE_NOT_FOUND = 1703,
-
- /**
- * The exchange found a wire fee that was above the total transfer value (and thus could not have been charged).
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TRANSFERS_GET_WIRE_FEE_INCONSISTENT = 1704,
-
- /**
- * The exchange responded with a reply that did not satsify the protocol. This error is not used in the protocol but created client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TRANSFERS_GET_REPLY_MALFORMED = 1705,
-
- /**
- * The exchange found internally inconsistent fee data when resolving a transaction in the database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSITS_GET_DB_FEE_INCONSISTENT = 1800,
-
- /**
- * The exchange encountered an error (that is not about not finding the transaction) trying to lookup a transaction in the database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSITS_GET_DB_FETCH_FAILED = 1801,
-
- /**
- * The exchange did not find information about the specified transaction in the database.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSITS_GET_NOT_FOUND = 1802,
-
- /**
- * The exchange failed to identify the wire transfer of the transaction (or information about the plan that it was supposed to still happen in the future).
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSITS_GET_WTID_RESOLUTION_ERROR = 1803,
-
- /**
- * The signature of the merchant is invalid.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSITS_GET_MERCHANT_SIGNATURE_INVALID = 1804,
-
- /**
- * The given denomination key is not in the "recoup" set of the exchange right now.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RECOUP_DENOMINATION_KEY_UNKNOWN = 1850,
-
- /**
- * The given coin signature is invalid for the request.
- * Returned with an HTTP status code of #MHD_HTTP_FORBIDDEN (403).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RECOUP_SIGNATURE_INVALID = 1851,
-
- /**
- * The signature of the denomination key over the coin is not valid.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RECOUP_DENOMINATION_SIGNATURE_INVALID = 1852,
-
- /**
- * The exchange failed to access its own database about reserves.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RECOUP_DB_FETCH_FAILED = 1853,
-
- /**
- * The exchange could not find the corresponding withdraw operation. The request is denied.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RECOUP_WITHDRAW_NOT_FOUND = 1854,
-
- /**
- * The exchange obtained an internally inconsistent transaction history for the given coin.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RECOUP_HISTORY_DB_ERROR = 1855,
-
- /**
- * The exchange failed to store information about the recoup to be performed in the database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RECOUP_DB_PUT_FAILED = 1856,
-
- /**
- * The coin's remaining balance is zero. The request is denied.
- * Returned with an HTTP status code of #MHD_HTTP_FORBIDDEN (403).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RECOUP_COIN_BALANCE_ZERO = 1857,
-
- /**
- * The exchange failed to reproduce the coin's blinding.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RECOUP_BLINDING_FAILED = 1858,
-
- /**
- * The coin's remaining balance is zero. The request is denied.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RECOUP_COIN_BALANCE_NEGATIVE = 1859,
-
- /**
- * Validity period of the denomination key is in the future.
- * Returned with an HTTP status code of #MHD_HTTP_PRECONDITION_FAILED (412).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RECOUP_DENOMINATION_VALIDITY_IN_FUTURE = 1860,
-
- /**
- * The exchange responded with a reply that did not satsify the protocol. This error is not used in the protocol but created client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RECOUP_REPLY_MALFORMED = 1861,
-
- /**
- * The "have" parameter was not a natural number.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- KEYS_HAVE_NOT_NUMERIC = 1900,
-
- /**
- * We currently cannot find any keys.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- KEYS_MISSING = 1901,
-
- /**
- * This exchange does not allow clients to request /keys for times other than the current (exchange) time.
- * Returned with an HTTP status code of #MHD_HTTP_FORBIDDEN (403).
- * (A value of 0 indicates that the error is generated client-side).
- */
- KEYS_TIMETRAVEL_FORBIDDEN = 1902,
-
- /**
- * The keys response was malformed. This error is generated client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- KEYS_INVALID = 1903,
-
- /**
- * The backend could not find the merchant instance specified in the request.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- INSTANCE_UNKNOWN = 2000,
-
- /**
- * The backend lacks a wire transfer method configuration option for the given instance.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PROPOSAL_INSTANCE_CONFIGURATION_LACKS_WIRE = 2002,
-
- /**
- * The merchant failed to provide a meaningful response to a /pay request. This error is created client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_MERCHANT_INVALID_RESPONSE = 2100,
-
- /**
- * The exchange responded saying that funds were insufficient (for example, due to double-spending).
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_INSUFFICIENT_FUNDS = 2101,
-
- /**
- * The merchant failed to commit the exchanges' response to a /deposit request to its database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_DB_STORE_PAY_ERROR = 2102,
-
- /**
- * The specified exchange is not supported/trusted by this merchant.
- * Returned with an HTTP status code of #MHD_HTTP_PRECONDITION_FAILED (412).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_EXCHANGE_REJECTED = 2103,
-
- /**
- * The denomination key used for payment is not listed among the denomination keys of the exchange.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_DENOMINATION_KEY_NOT_FOUND = 2104,
-
- /**
- * The denomination key used for payment is not audited by an auditor approved by the merchant.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_DENOMINATION_KEY_AUDITOR_FAILURE = 2105,
-
- /**
- * There was an integer overflow totaling up the amounts or deposit fees in the payment.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_AMOUNT_OVERFLOW = 2106,
-
- /**
- * The deposit fees exceed the total value of the payment.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_FEES_EXCEED_PAYMENT = 2107,
-
- /**
- * After considering deposit and wire fees, the payment is insufficient to satisfy the required amount for the contract. The client should revisit the logic used to calculate fees it must cover.
- * Returned with an HTTP status code of #MHD_HTTP_ACCEPTED (202).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_PAYMENT_INSUFFICIENT_DUE_TO_FEES = 2108,
-
- /**
- * Even if we do not consider deposit and wire fees, the payment is insufficient to satisfy the required amount for the contract.
- * Returned with an HTTP status code of #MHD_HTTP_ACCEPTED (202).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_PAYMENT_INSUFFICIENT = 2109,
-
- /**
- * The signature over the contract of one of the coins was invalid.
- * Returned with an HTTP status code of #MHD_HTTP_FORBIDDEN (403).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_COIN_SIGNATURE_INVALID = 2110,
-
- /**
- * We failed to contact the exchange for the /pay request.
- * Returned with an HTTP status code of #MHD_HTTP_REQUEST_TIMEOUT (408).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_EXCHANGE_TIMEOUT = 2111,
-
- /**
- * When we tried to find information about the exchange to issue the deposit, we failed. This usually only happens if the merchant backend is somehow unable to get its own HTTP client logic to work.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_EXCHANGE_LOOKUP_FAILED = 2112,
-
- /**
- * The refund deadline in the contract is after the transfer deadline.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_REFUND_DEADLINE_PAST_WIRE_TRANSFER_DEADLINE = 2114,
-
- /**
- * The request fails to provide coins for the payment.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_COINS_ARRAY_EMPTY = 2115,
-
- /**
- * The merchant failed to fetch the contract terms from the merchant's database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_DB_FETCH_PAY_ERROR = 2116,
-
- /**
- * The merchant failed to fetch the merchant's previous state with respect to transactions from its database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_DB_FETCH_TRANSACTION_ERROR = 2117,
-
- /**
- * The merchant failed to store the merchant's state with respect to the transaction in its database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_DB_STORE_TRANSACTION_ERROR = 2119,
-
- /**
- * The exchange failed to provide a valid response to the merchant's /keys request.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_EXCHANGE_KEYS_FAILURE = 2120,
-
- /**
- * The payment is too late, the offer has expired.
- * Returned with an HTTP status code of #MHD_HTTP_GONE (410).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_OFFER_EXPIRED = 2121,
-
- /**
- * The "merchant" field is missing in the proposal data.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_MERCHANT_FIELD_MISSING = 2122,
-
- /**
- * Failed computing a hash code (likely server out-of-memory).
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_FAILED_COMPUTE_PROPOSAL_HASH = 2123,
-
- /**
- * Failed to locate merchant's account information matching the wire hash given in the proposal.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_WIRE_HASH_UNKNOWN = 2124,
-
- /**
- * We got different currencies for the wire fee and the maximum wire fee.
- * Returned with an HTTP status code of #MHD_HTTP_PRECONDITION_FAILED (412).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_WIRE_FEE_CURRENCY_MISMATCH = 2125,
-
- /**
- * The exchange had a failure when trying to process the request, returning a malformed response.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_EXCHANGE_REPLY_MALFORMED = 2126,
-
- /**
- * A unknown merchant public key was included in the payment. That happens typically when the wallet sends the payment to the wrong merchant instance.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_WRONG_INSTANCE = 2127,
-
- /**
- * The exchange failed to give us a response when we asked for /keys.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_EXCHANGE_HAS_NO_KEYS = 2128,
-
- /**
- * The deposit time for the denomination has expired.
- * Returned with an HTTP status code of #MHD_HTTP_GONE (410).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_DENOMINATION_DEPOSIT_EXPIRED = 2129,
-
- /**
- * The proposal is not known to the backend.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_PROPOSAL_NOT_FOUND = 2130,
-
- /**
- * The exchange of the deposited coin charges a wire fee that could not be added to the total (total amount too high).
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_EXCHANGE_WIRE_FEE_ADDITION_FAILED = 2131,
-
- /**
- * The contract was not fully paid because of refunds. Note that clients MAY treat this as paid if, for example, contracts must be executed despite of refunds.
- * Returned with an HTTP status code of #MHD_HTTP_PAYMENT_REQUIRED (402).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_REFUNDED = 2132,
-
- /**
- * According to our database, we have refunded more than we were paid (which should not be possible).
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_REFUNDS_EXCEED_PAYMENTS = 2133,
-
- /**
- * Legacy stuff. Remove me with protocol v1.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_ABORT_REFUND_REFUSED_PAYMENT_COMPLETE = 2134,
-
- /**
- * The payment failed at the exchange.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_EXCHANGE_FAILED = 2135,
-
- /**
- * The merchant backend couldn't verify the order payment because of a database failure.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAID_DB_ERROR = 2146,
-
- /**
- * The order is not known.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAID_ORDER_UNKNOWN = 2147,
-
- /**
- * The contract hash does not match the given order ID.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAID_CONTRACT_HASH_MISMATCH = 2148,
-
- /**
- * The signature of the merchant is not valid for the given contract hash.
- * Returned with an HTTP status code of #MHD_HTTP_FORBIDDEN (403).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAID_COIN_SIGNATURE_INVALID = 2149,
-
- /**
- * The merchant failed to contact the exchange.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ABORT_EXCHANGE_KEYS_FAILURE = 2150,
-
- /**
- * The merchant failed to send the exchange the refund request.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ABORT_EXCHANGE_REFUND_FAILED = 2151,
-
- /**
- * The merchant failed to find the exchange to process the lookup.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ABORT_EXCHANGE_LOOKUP_FAILED = 2152,
-
- /**
- * The merchant failed to store the abort request in its database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ABORT_DB_STORE_ABORT_ERROR = 2153,
-
- /**
- * The merchant failed to repeatedly serialize the transaction.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ABORT_DB_STORE_TRANSACTION_ERROR = 2154,
-
- /**
- * The merchant failed in the lookup part of the transaction.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ABORT_DB_FETCH_TRANSACTION_ERROR = 2155,
-
- /**
- * The merchant could not find the contract.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ABORT_CONTRACT_NOT_FOUND = 2156,
-
- /**
- * The payment was already completed and thus cannot be aborted anymore.
- * Returned with an HTTP status code of #MHD_HTTP_PRECONDITION_FAILED (412).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ABORT_REFUND_REFUSED_PAYMENT_COMPLETE = 2157,
-
- /**
- * The hash provided by the wallet does not match the order.
- * Returned with an HTTP status code of #MHD_HTTP_FORBIDDEN (403).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ABORT_CONTRACT_HASH_MISSMATCH = 2158,
-
- /**
- * The array of coins cannot be empty.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ABORT_COINS_ARRAY_EMPTY = 2159,
-
- /**
- * The merchant experienced a timeout processing the request.
- * Returned with an HTTP status code of #MHD_HTTP_REQUEST_TIMEOUT (408).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ABORT_EXCHANGE_TIMEOUT = 2160,
-
- /**
- * The merchant could not find the order.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- FORGET_ORDER_NOT_FOUND = 2180,
-
- /**
- * One of the paths to forget is malformed.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- FORGET_PATH_SYNTAX_INCORRECT = 2181,
-
- /**
- * One of the paths to forget was not marked as forgettable.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- FORGET_PATH_NOT_FORGETTABLE = 2182,
-
- /**
- * Integer overflow with specified timestamp argument detected.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- HISTORY_TIMESTAMP_OVERFLOW = 2200,
-
- /**
- * Failed to retrieve history from merchant database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- HISTORY_DB_FETCH_ERROR = 2201,
-
- /**
- * The backend could not find the contract specified in the request.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POLL_PAYMENT_CONTRACT_NOT_FOUND = 2250,
-
- /**
- * The response provided by the merchant backend was malformed. This error is created client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POLL_PAYMENT_REPLY_MALFORMED = 2251,
-
- /**
- * We failed to contact the exchange for the /track/transaction request.
- * Returned with an HTTP status code of #MHD_HTTP_SERVICE_UNAVAILABLE (503).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TRACK_TRANSACTION_EXCHANGE_TIMEOUT = 2300,
-
- /**
- * We failed to get a valid /keys response from the exchange for the /track/transaction request.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TRACK_TRANSACTION_EXCHANGE_KEYS_FAILURE = 2301,
-
- /**
- * The backend could not find the transaction specified in the request.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TRACK_TRANSACTION_TRANSACTION_UNKNOWN = 2302,
-
- /**
- * The backend had a database access error trying to retrieve transaction data from its database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TRACK_TRANSACTION_DB_FETCH_TRANSACTION_ERROR = 2303,
-
- /**
- * The backend had a database access error trying to retrieve payment data from its database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TRACK_TRANSACTION_DB_FETCH_PAYMENT_ERROR = 2304,
-
- /**
- * The backend found no applicable deposits in the database. This is odd, as we know about the transaction, but not about deposits we made for the transaction.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TRACK_TRANSACTION_DB_NO_DEPOSITS_ERROR = 2305,
-
- /**
- * We failed to obtain a wire transfer identifier for one of the coins in the transaction.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TRACK_TRANSACTION_COIN_TRACE_ERROR = 2306,
-
- /**
- * We failed to obtain the full wire transfer identifier for the transfer one of the coins was aggregated into.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TRACK_TRANSACTION_WIRE_TRANSFER_TRACE_ERROR = 2307,
-
- /**
- * We got conflicting reports from the exhange with respect to which transfers are included in which aggregate.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TRACK_TRANSACTION_CONFLICTING_REPORTS = 2308,
-
- /**
- * We did failed to retrieve information from our database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_TRANSFERS_DB_FETCH_ERROR = 2350,
-
- /**
- * We failed to contact the exchange for the /track/transfer request.
- * Returned with an HTTP status code of #MHD_HTTP_SERVICE_UNAVAILABLE (503).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POST_TRANSFERS_EXCHANGE_TIMEOUT = 2400,
-
- /**
- * We failed to obtain an acceptable /keys response from the exchange for the /track/transfer request.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POST_TRANSFERS_EXCHANGE_KEYS_FAILURE = 2401,
-
- /**
- * We failed to persist coin wire transfer information in our merchant database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POST_TRANSFERS_DB_STORE_COIN_ERROR = 2402,
-
- /**
- * We internally failed to execute the /track/transfer request.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POST_TRANSFERS_REQUEST_ERROR = 2403,
-
- /**
- * We failed to persist wire transfer information in our merchant database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POST_TRANSFERS_DB_STORE_TRANSFER_ERROR = 2404,
-
- /**
- * The exchange returned an error from /track/transfer.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POST_TRANSFERS_EXCHANGE_ERROR = 2405,
-
- /**
- * We failed to fetch deposit information from our merchant database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POST_TRANSFERS_DB_FETCH_DEPOSIT_ERROR = 2406,
-
- /**
- * We encountered an internal logic error.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POST_TRANSFERS_DB_INTERNAL_LOGIC_ERROR = 2407,
-
- /**
- * The exchange gave conflicting information about a coin which has been wire transferred.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POST_TRANSFERS_CONFLICTING_REPORTS = 2408,
-
- /**
- * The merchant backend had problems in creating the JSON response.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POST_TRANSFERS_JSON_RESPONSE_ERROR = 2409,
-
- /**
- * The exchange charged a different wire fee than what it originally advertised, and it is higher.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POST_TRANSFERS_JSON_BAD_WIRE_FEE = 2410,
-
- /**
- * We did not find the account that the transfer was made to.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POST_TRANSFERS_ACCOUNT_NOT_FOUND = 2411,
-
- /**
- * We did failed to store information in our database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POST_TRANSFERS_DB_STORE_ERROR = 2412,
-
- /**
- * We did failed to retrieve information from our database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POST_TRANSFERS_DB_LOOKUP_ERROR = 2413,
-
- /**
- * The merchant backend cannot create an instance under the given identifier as one already exists. Use PATCH to modify the existing entry.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POST_INSTANCES_ALREADY_EXISTS = 2450,
-
- /**
- * The merchant backend cannot create an instance because the specified bank accounts are somehow invalid.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POST_INSTANCES_BAD_PAYTO_URIS = 2451,
-
- /**
- * The merchant backend cannot create an instance because it failed to start the database transaction.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POST_INSTANCES_DB_START_ERROR = 2452,
-
- /**
- * The merchant backend cannot create an instance because it failed to commit the database transaction.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- POST_INSTANCES_DB_COMMIT_ERROR = 2453,
-
- /**
- * The merchant backend cannot delete an instance because it failed to commit the database transaction.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DELETE_INSTANCES_ID_DB_HARD_FAILURE = 2454,
-
- /**
- * The merchant backend cannot delete the data because it already does not exist.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DELETE_INSTANCES_ID_NO_SUCH_INSTANCE = 2455,
-
- /**
- * The merchant backend cannot update an instance because the specified bank accounts are somehow invalid.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PATCH_INSTANCES_BAD_PAYTO_URIS = 2456,
-
- /**
- * The merchant backend cannot patch an instance because it failed to start the database transaction.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PATCH_INSTANCES_DB_START_ERROR = 2457,
-
- /**
- * The merchant backend cannot patch an instance because it failed to commit the database transaction.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PATCH_INSTANCES_DB_COMMIT_ERROR = 2458,
-
- /**
- * The hash provided in the request of /map/in does not match the contract sent alongside in the same request.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- MAP_IN_UNMATCHED_HASH = 2500,
-
- /**
- * The backend encountered an error while trying to store the h_contract_terms into the database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PROPOSAL_STORE_DB_ERROR = 2501,
-
- /**
- * The backend encountered an error while trying to retrieve the proposal data from database. Likely to be an internal error.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PROPOSAL_LOOKUP_DB_ERROR = 2502,
-
- /**
- * The proposal being looked up is not found on this merchant.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PROPOSAL_LOOKUP_NOT_FOUND = 2503,
-
- /**
- * The proposal had no timestamp and the backend failed to obtain the local time. Likely to be an internal error.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PROPOSAL_NO_LOCALTIME = 2504,
-
- /**
- * The order provided to the backend could not be parsed, some required fields were missing or ill-formed.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PROPOSAL_ORDER_PARSE_ERROR = 2505,
-
- /**
- * The backend encountered an error while trying to find the existing proposal in the database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PROPOSAL_STORE_DB_ERROR_HARD = 2506,
-
- /**
- * The backend encountered an error while trying to find the existing proposal in the database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PROPOSAL_STORE_DB_ERROR_SOFT = 2507,
-
- /**
- * The backend encountered an error: the proposal already exists.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PROPOSAL_STORE_DB_ERROR_ALREADY_EXISTS = 2508,
-
- /**
- * The order provided to the backend uses an amount in a currency that does not match the backend's configuration.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PROPOSAL_ORDER_BAD_CURRENCY = 2509,
-
- /**
- * The response provided by the merchant backend was malformed. This error is created client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PROPOSAL_REPLY_MALFORMED = 2510,
-
- /**
- * The order provided to the backend could not be deleted, it is not known.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ORDERS_DELETE_NO_SUCH_ORDER = 2511,
-
- /**
- * The order provided to the backend could not be deleted, our offer is still valid and awaiting payment.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ORDERS_DELETE_AWAITING_PAYMENT = 2512,
-
- /**
- * The order provided to the backend could not be deleted, due to a database error.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ORDERS_DELETE_DB_HARD_FAILURE = 2513,
-
- /**
- * The order provided to the backend could not be completed, due to a database error trying to fetch product inventory data.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ORDERS_LOOKUP_PRODUCT_DB_HARD_FAILURE = 2514,
-
- /**
- * The order provided to the backend could not be completed, due to a database serialization error (which should be impossible) trying to fetch product inventory data.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ORDERS_LOOKUP_PRODUCT_DB_SOFT_FAILURE = 2515,
-
- /**
- * The order provided to the backend could not be completed, because a product to be completed via inventory data is not actually in our inventory.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ORDERS_LOOKUP_PRODUCT_NOT_FOUND = 2516,
-
- /**
- * We could not obtain a list of all orders because of a database failure.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ORDERS_GET_DB_LOOKUP_ERROR = 2517,
-
- /**
- * We could not claim the order because of a database failure.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ORDERS_CLAIM_HARD_DB_ERROR = 2518,
-
- /**
- * We could not claim the order because of a database serialization failure.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ORDERS_CLAIM_SOFT_DB_ERROR = 2519,
-
- /**
- * We could not claim the order because the backend is unaware of it.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ORDERS_CLAIM_NOT_FOUND = 2520,
-
- /**
- * We could not claim the order because someone else claimed it first.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- ORDERS_ALREADY_CLAIMED = 2521,
-
- /**
- * The merchant backend failed to lookup the products.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_PRODUCTS_DB_LOOKUP_ERROR = 2550,
-
- /**
- * The merchant backend failed to start the transaction.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PRODUCTS_POST_DB_START_ERROR = 2551,
-
- /**
- * The product ID exists.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PRODUCTS_POST_CONFLICT_PRODUCT_EXISTS = 2552,
-
- /**
- * The merchant backend failed to serialize the transaction.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PRODUCTS_POST_DB_COMMIT_SOFT_ERROR = 2553,
-
- /**
- * The merchant backend failed to commit the transaction.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PRODUCTS_POST_DB_COMMIT_HARD_ERROR = 2554,
-
- /**
- * The merchant backend failed to commit the transaction.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PRODUCTS_PATCH_DB_COMMIT_HARD_ERROR = 2555,
-
- /**
- * The merchant backend did not find the product to be updated.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PRODUCTS_PATCH_UNKNOWN_PRODUCT = 2556,
-
- /**
- * The update would have reduced the total amount of product lost, which is not allowed.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PRODUCTS_PATCH_TOTAL_LOST_REDUCED = 2557,
-
- /**
- * The update would have mean that more stocks were lost than what remains from total inventory after sales, which is not allowed.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PRODUCTS_PATCH_TOTAL_LOST_EXCEEDS_STOCKS = 2558,
-
- /**
- * The update would have reduced the total amount of product in stock, which is not allowed.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PRODUCTS_PATCH_TOTAL_STOCKED_REDUCED = 2559,
-
- /**
- * The lock request is for more products than we have left (unlocked) in stock.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PRODUCTS_LOCK_INSUFFICIENT_STOCKS = 2560,
-
- /**
- * The lock request is for an unknown product.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PRODUCTS_LOCK_UNKNOWN_PRODUCT = 2561,
-
- /**
- * The deletion request resulted in a hard database error.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PRODUCTS_DELETE_DB_HARD_FAILURE = 2562,
-
- /**
- * The deletion request was for a product unknown to the backend.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PRODUCTS_DELETE_NO_SUCH_PRODUCT = 2563,
-
- /**
- * The deletion request is for a product that is locked.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PRODUCTS_DELETE_CONFLICTING_LOCK = 2564,
-
- /**
- * The merchant returned a malformed response. Error created client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_LOOKUP_INVALID_RESPONSE = 2600,
-
- /**
- * The frontend gave an unknown order id to issue the refund to.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_ORDER_ID_UNKNOWN = 2601,
-
- /**
- * The amount to be refunded is inconsistent: either is lower than the previous amount being awarded, or it is too big to be paid back. In this second case, the fault stays on the business dept. side.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_INCONSISTENT_AMOUNT = 2602,
-
- /**
- * The backend encountered an error while trying to retrieve the payment data from database. Likely to be an internal error.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_LOOKUP_DB_ERROR = 2603,
-
- /**
- * The backend encountered an error while trying to retrieve the payment data from database. Likely to be an internal error.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_MERCHANT_DB_COMMIT_ERROR = 2604,
-
- /**
- * Payments are stored in a single db transaction; this error indicates that one db operation within that transaction failed. This might involve storing of coins or other related db operations, like starting/committing the db transaction or marking a contract as paid.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_DB_STORE_PAYMENTS_ERROR = 2605,
-
- /**
- * The backend failed to sign the refund request.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- PAY_REFUND_SIGNATURE_FAILED = 2606,
-
- /**
- * The merchant backend is not available of any applicable refund(s) for this order.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_LOOKUP_NO_REFUND = 2607,
-
- /**
- * The frontend gave an unpaid order id to issue the refund to.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- REFUND_ORDER_ID_UNPAID = 2608,
-
- /**
- * The requested wire method is not supported by the exchange.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RESERVES_POST_UNSUPPORTED_WIRE_METHOD = 2650,
-
- /**
- * The backend failed to commit the result to the database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RESERVES_POST_DB_COMMIT_HARD_ERROR = 2651,
-
- /**
- * The backend failed to fetch the requested information from the database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_RESERVES_DB_LOOKUP_ERROR = 2652,
-
- /**
- * The backend knows the instance that was supposed to support the tip, but it was not configured for tipping (i.e. has no exchange associated with it). Likely to be a configuration error.
- * Returned with an HTTP status code of #MHD_HTTP_PRECONDITION_FAILED (412).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_AUTHORIZE_INSTANCE_DOES_NOT_TIP = 2701,
-
- /**
- * The reserve that was used to fund the tips has expired.
- * Returned with an HTTP status code of #MHD_HTTP_GONE (410).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_AUTHORIZE_RESERVE_EXPIRED = 2702,
-
- /**
- * The reserve that was used to fund the tips was not found in the DB.
- * Returned with an HTTP status code of #MHD_HTTP_SERVICE_UNAVAILABLE (503).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_AUTHORIZE_RESERVE_UNKNOWN = 2703,
-
- /**
- * The backend knows the instance that was supposed to support the tip, and it was configured for tipping. However, the funds remaining are insufficient to cover the tip, and the merchant should top up the reserve.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_AUTHORIZE_INSUFFICIENT_FUNDS = 2704,
-
- /**
- * The backend had trouble accessing the database to persist information about the tip authorization. Returned with an HTTP status code of internal error.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_AUTHORIZE_DB_HARD_ERROR = 2705,
-
- /**
- * The backend had trouble accessing the database to persist information about the tip authorization. The problem might be fixable by repeating the transaction.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_AUTHORIZE_DB_SOFT_ERROR = 2706,
-
- /**
- * The backend failed to obtain a reserve status from the exchange.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_QUERY_RESERVE_STATUS_FAILED_EXCHANGE_DOWN = 2707,
-
- /**
- * The backend got an empty (!) reserve history from the exchange.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_QUERY_RESERVE_HISTORY_FAILED_EMPTY = 2708,
-
- /**
- * The backend got an invalid reserve history (fails to start with a deposit) from the exchange.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_QUERY_RESERVE_HISTORY_INVALID_NO_DEPOSIT = 2709,
-
- /**
- * The backend got an 404 response from the exchange when it inquired about the reserve history.
- * Returned with an HTTP status code of #MHD_HTTP_SERVICE_UNAVAILABLE (503).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_QUERY_RESERVE_UNKNOWN_TO_EXCHANGE = 2710,
-
- /**
- * The backend got a reserve with a currency that does not match the backend's currency.
- * Returned with an HTTP status code of #MHD_HTTP_SERVICE_UNAVAILABLE (503).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_QUERY_RESERVE_CURRENCY_MISMATCH = 2711,
-
- /**
- * The backend got a reserve history with amounts it cannot process (addition failure in deposits).
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_QUERY_RESERVE_HISTORY_ARITHMETIC_ISSUE_DEPOSIT = 2712,
-
- /**
- * The backend got a reserve history with amounts it cannot process (addition failure in withdraw amounts).
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_QUERY_RESERVE_HISTORY_ARITHMETIC_ISSUE_WITHDRAW = 2713,
-
- /**
- * The backend got a reserve history with amounts it cannot process (addition failure in closing amounts).
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_QUERY_RESERVE_HISTORY_ARITHMETIC_ISSUE_CLOSED = 2714,
-
- /**
- * The backend got a reserve history with inconsistent amounts.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_QUERY_RESERVE_HISTORY_ARITHMETIC_ISSUE_INCONSISTENT = 2715,
-
- /**
- * The backend encountered a database error querying tipping reserves.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_QUERY_DB_ERROR = 2716,
-
- /**
- * The backend got an unexpected resever history reply from the exchange.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_QUERY_RESERVE_HISTORY_FAILED = 2717,
-
- /**
- * The backend got a reserve history with amounts it cannot process (addition failure in withdraw amounts).
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_QUERY_RESERVE_HISTORY_ARITHMETIC_ISSUE_RECOUP = 2718,
-
- /**
- * The backend knows the instance that was supposed to support the tip, but it was not configured for tipping (i.e. has no exchange associated with it). Likely to be a configuration error.
- * Returned with an HTTP status code of #MHD_HTTP_PRECONDITION_FAILED (412).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_QUERY_INSTANCE_DOES_NOT_TIP = 2719,
-
- /**
- * The tip id is unknown. This could happen if the tip id is wrong or the tip authorization expired.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_QUERY_TIP_ID_UNKNOWN = 2720,
-
- /**
- * The reserve could not be deleted due to a database failure.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RESERVES_DELETE_DB_HARD_FAILURE = 2721,
-
- /**
- * The reserve could not be deleted because it is unknown.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- RESERVES_DELETE_NO_SUCH_RESERVE = 2722,
-
- /**
- * The backend got an unexpected error trying to lookup reserve details from the backend.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_LOOKUP_RESERVE_DB_FAILURE = 2723,
-
- /**
- * The backend repeatedly failed to serialize the transaction to authorize the tip.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_AUTHORIZE_DB_SERIALIZATION_FAILURE = 2724,
-
- /**
- * The backend failed to start the transaction to authorize the tip.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_AUTHORIZE_DB_START_FAILURE = 2725,
-
- /**
- * The backend failed looking up the reserve needed to authorize the tip.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_AUTHORIZE_DB_LOOKUP_RESERVE_FAILURE = 2726,
-
- /**
- * The backend failed to find a reserve needed to authorize the tip.
- * Returned with an HTTP status code of #MHD_HTTP_SERVICE_UNAVAILABLE (503).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_AUTHORIZE_DB_RESERVE_NOT_FOUND = 2727,
-
- /**
- * The backend encountered an internal invariant violation.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_AUTHORIZE_DB_RESERVE_INVARIANT_FAILURE = 2728,
-
- /**
- * The selected exchange expired.
- * Returned with an HTTP status code of #MHD_HTTP_GONE (410).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_AUTHORIZE_DB_RESERVE_EXPIRED = 2729,
-
- /**
- * The backend failed updating the reserve needed to authorize the tip.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_AUTHORIZE_DB_UPDATE_RESERVE_FAILURE = 2730,
-
- /**
- * The backend had trouble accessing the database to persist information about enabling tips. Returned with an HTTP status code of internal error.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_ENABLE_DB_TRANSACTION_ERROR = 2750,
-
- /**
- * The tip ID is unknown. This could happen if the tip has expired.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_TIP_ID_UNKNOWN = 2800,
-
- /**
- * The amount requested exceeds the remaining tipping balance for this tip ID. Returned with an HTTP status code of "Conflict" (as it conflicts with a previous pickup operation).
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_NO_FUNDS = 2801,
-
- /**
- * We encountered a DB error, repeating the request may work.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_DB_ERROR_SOFT = 2802,
-
- /**
- * We encountered a DB error, repeating the request will not help. This is an internal server error.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_DB_ERROR_HARD = 2803,
-
- /**
- * The same pickup ID was already used for picking up a different amount. This points to a very strange internal error as the pickup ID is derived from the denomination key which is tied to a particular amount. Hence this should also be an internal server error.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_AMOUNT_CHANGED = 2804,
-
- /**
- * We failed to contact the exchange to obtain the denomination keys.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_EXCHANGE_DOWN = 2805,
-
- /**
- * We contacted the exchange to obtain any denomination keys, but got no valid keys.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_EXCHANGE_LACKED_KEYS = 2806,
-
- /**
- * We contacted the exchange to obtain at least one of the denomination keys specified in the request. Returned with a response code "not found" (404).
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_EXCHANGE_LACKED_KEY = 2807,
-
- /**
- * We encountered an arithmetic issue totaling up the amount to withdraw.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_EXCHANGE_AMOUNT_OVERFLOW = 2808,
-
- /**
- * The number of planchets specified exceeded the limit.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_EXCHANGE_TOO_MANY_PLANCHETS = 2809,
-
- /**
- * The merchant failed to initialize the withdraw operation.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_WITHDRAW_FAILED = 2810,
-
- /**
- * The merchant failed to initialize the withdraw operation.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_WITHDRAW_FAILED_AT_EXCHANGE = 2811,
-
- /**
- * The client failed to unblind the signature returned by the merchant. Generated client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_UNBLIND_FAILURE = 2812,
-
- /**
- * Merchant failed to access its database to lookup the tip.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_TIPS_DB_LOOKUP_ERROR = 2813,
-
- /**
- * Merchant failed find the tip in its database.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_TIPS_ID_UNKNOWN = 2814,
-
- /**
- * The merchant failed to contact the exchange.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_CONTACT_EXCHANGE_ERROR = 2815,
-
- /**
- * The merchant failed to obtain keys from the exchange.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_EXCHANGE_KEYS_ERROR = 2816,
-
- /**
- * The merchant failed to store data in its own database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_DB_STORE_HARD_ERROR = 2817,
-
- /**
- * The merchant failed to get a timely response from the exchange.
- * Returned with an HTTP status code of #MHD_HTTP_REQUEST_TIMEOUT (408).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_EXCHANGE_TIMEOUT = 2818,
-
- /**
- * The exchange returned a failure code for the withdraw operation.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_EXCHANGE_ERROR = 2819,
-
- /**
- * The merchant failed to add up the amounts to compute the pick up value.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_SUMMATION_FAILED = 2820,
-
- /**
- * The tip expired.
- * Returned with an HTTP status code of #MHD_HTTP_GONE (410).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_HAS_EXPIRED = 2821,
-
- /**
- * The requested withdraw amount exceeds the amount remaining to be picked up.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_AMOUNT_EXCEEDS_TIP_REMAINING = 2822,
-
- /**
- * The merchant failed to store data in its own database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_DB_STORE_SOFT_ERROR = 2823,
-
- /**
- * The merchant did not find the specified denomination key in the exchange's key set.
- * Returned with an HTTP status code of #MHD_HTTP_CONFLICT (409).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TIP_PICKUP_DENOMINATION_UNKNOWN = 2824,
-
- /**
- * We failed to fetch contract terms from our merchant database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_ORDERS_DB_LOOKUP_ERROR = 2900,
-
- /**
- * We failed to find the contract terms from our merchant database.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_ORDERS_ID_UNKNOWN = 2901,
-
- /**
- * The merchant had a timeout contacting the exchange, thus not providing wire details in the response.
- * Returned with an HTTP status code of #MHD_HTTP_REQUEST_TIMEOUT (408).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_ORDERS_EXCHANGE_TIMEOUT = 2902,
-
- /**
- * The exchange failed to provide a valid answer to the tracking request, thus those details are not in the response.
- * Returned with an HTTP status code of #MHD_HTTP_OK (200).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_ORDERS_EXCHANGE_TRACKING_FAILURE = 2903,
-
- /**
- * The merchant backend failed to persist tracking details in its database, thus those details are not in the response.
- * Returned with an HTTP status code of #MHD_HTTP_OK (200).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_ORDERS_DB_STORE_TRACKING_FAILURE = 2904,
-
- /**
- * The merchant backend encountered a failure in computing the deposit total.
- * Returned with an HTTP status code of #MHD_HTTP_OK (200).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_ORDERS_AMOUNT_ARITHMETIC_FAILURE = 2905,
-
- /**
- * The merchant backend failed trying to contact the exchange for tracking details, thus those details are not in the response.
- * Returned with an HTTP status code of #MHD_HTTP_FAILED_DEPENDENCY (424).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_ORDERS_EXCHANGE_LOOKUP_FAILURE = 2906,
-
- /**
- * The merchant backend failed to construct the request for tracking to the exchange, thus tracking details are not in the response.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_ORDERS_EXCHANGE_REQUEST_FAILURE = 2907,
-
- /**
- * The merchant backend had a database failure trying to find information about the contract of the order.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_ORDERS_DB_FETCH_CONTRACT_TERMS_ERROR = 2908,
-
- /**
- * The merchant backend could not find an order with the given identifier.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_ORDERS_ORDER_NOT_FOUND = 2909,
-
- /**
- * The merchant backend could not compute the hash of the proposal.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_ORDERS_FAILED_COMPUTE_PROPOSAL_HASH = 2910,
-
- /**
- * The merchant backend could not fetch the payment status from its database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_ORDERS_DB_FETCH_PAYMENT_STATUS = 2911,
-
- /**
- * The merchant backend had an error looking up information in its database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_ORDERS_DB_FETCH_TRANSACTION_ERROR = 2912,
-
- /**
- * The contract obtained from the merchant backend was malformed.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_ORDERS_CONTRACT_CONTENT_INVALID = 2913,
-
- /**
- * We failed to contract terms from our merchant database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- CHECK_PAYMENT_DB_FETCH_CONTRACT_TERMS_ERROR = 2914,
-
- /**
- * We failed to contract terms from our merchant database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- CHECK_PAYMENT_DB_FETCH_ORDER_ERROR = 2915,
-
- /**
- * The order id we're checking is unknown, likely the frontend did not create the order first.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- CHECK_PAYMENT_ORDER_ID_UNKNOWN = 2916,
-
- /**
- * Failed computing a hash code (likely server out-of-memory).
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- CHECK_PAYMENT_FAILED_COMPUTE_PROPOSAL_HASH = 2917,
-
- /**
- * Signature "session_sig" failed to verify.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- CHECK_PAYMENT_SESSION_SIGNATURE_INVALID = 2918,
-
- /**
- * The order we found does not match the provided contract hash.
- * Returned with an HTTP status code of #MHD_HTTP_FORBIDDEN (403).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_ORDER_WRONG_CONTRACT = 2919,
-
- /**
- * The response we received from the merchant is malformed. This error is generated client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- CHECK_PAYMENT_RESPONSE_MALFORMED = 2920,
-
- /**
- * The merchant backend failed trying to contact the exchange for tracking details, thus those details are not in the response.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- GET_ORDERS_EXCHANGE_LOOKUP_START_FAILURE = 2921,
-
- /**
- * The response we received from the merchant is malformed. This error is generated client-side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- MERCHANT_ORDER_GET_REPLY_MALFORMED = 2922,
-
- /**
- * The token used to authenticate the client is invalid for this order.
- * Returned with an HTTP status code of #MHD_HTTP_FORBIDDEN (403).
- * (A value of 0 indicates that the error is generated client-side).
- */
- MERCHANT_GET_ORDER_INVALID_TOKEN = 2923,
-
- /**
- * The signature from the exchange on the deposit confirmation is invalid. Returned with a "400 Bad Request" status code.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_CONFIRMATION_SIGNATURE_INVALID = 3000,
-
- /**
- * The auditor had trouble storing the deposit confirmation in its database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- DEPOSIT_CONFIRMATION_STORE_DB_ERROR = 3001,
-
- /**
- * The auditor had trouble retrieving the exchange list from its database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- LIST_EXCHANGES_DB_ERROR = 3002,
-
- /**
- * The auditor had trouble storing an exchange in its database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- AUDITOR_EXCHANGE_STORE_DB_ERROR = 3003,
-
- /**
- * The auditor (!) responded with a reply that did not satsify the protocol. This error is not used in the protocol but created client- side.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- AUDITOR_EXCHANGES_REPLY_MALFORMED = 3004,
-
- /**
- * The exchange failed to compute ECDH.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TEST_ECDH_ERROR = 4000,
-
- /**
- * The EdDSA test signature is invalid.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TEST_EDDSA_INVALID = 4001,
-
- /**
- * The exchange failed to compute the EdDSA test signature.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TEST_EDDSA_ERROR = 4002,
-
- /**
- * The exchange failed to generate an RSA key.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TEST_RSA_GEN_ERROR = 4003,
-
- /**
- * The exchange failed to compute the public RSA key.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TEST_RSA_PUB_ERROR = 4004,
-
- /**
- * The exchange failed to compute the RSA signature.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- TEST_RSA_SIGN_ERROR = 4005,
-
- /**
- * The JSON in the server's response was malformed. This response is provided with HTTP status code of 0.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SERVER_JSON_INVALID = 5000,
-
- /**
- * A signature in the server's response was malformed. This response is provided with HTTP status code of 0.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SERVER_SIGNATURE_INVALID = 5001,
-
- /**
- * Wire transfer attempted with credit and debit party being the same bank account.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- BANK_SAME_ACCOUNT = 5102,
-
- /**
- * Wire transfer impossible, due to financial limitation of the party that attempted the payment.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- BANK_UNALLOWED_DEBIT = 5103,
-
- /**
- * Arithmetic operation between two amounts of different currency was attempted.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- BANK_CURRENCY_MISMATCH = 5104,
-
- /**
- * At least one GET parameter was either missing or invalid for the requested operation.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- BANK_PARAMETER_MISSING_OR_INVALID = 5105,
-
- /**
- * JSON body sent was invalid for the requested operation.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- BANK_JSON_INVALID = 5106,
-
- /**
- * Negative number was used (as value and/or fraction) to initiate a Amount object.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- BANK_NEGATIVE_NUMBER_AMOUNT = 5107,
-
- /**
- * A number too big was used (as value and/or fraction) to initiate a amount object.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- BANK_NUMBER_TOO_BIG = 5108,
-
- /**
- * Could not login for the requested operation.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- BANK_LOGIN_FAILED = 5109,
-
- /**
- * The bank account referenced in the requested operation was not found. Returned along "400 Not found".
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- BANK_UNKNOWN_ACCOUNT = 5110,
-
- /**
- * The transaction referenced in the requested operation (typically a reject operation), was not found.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- BANK_TRANSACTION_NOT_FOUND = 5111,
-
- /**
- * Bank received a malformed amount string.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- BANK_BAD_FORMAT_AMOUNT = 5112,
-
- /**
- * The client does not own the account credited by the transaction which is to be rejected, so it has no rights do reject it. To be returned along HTTP 403 Forbidden.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- BANK_REJECT_NO_RIGHTS = 5200,
-
- /**
- * This error code is returned when no known exception types captured the exception, and comes along with a 500 Internal Server Error.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- BANK_UNMANAGED_EXCEPTION = 5300,
-
- /**
- * This error code is used for all those exceptions that do not really need a specific error code to return to the client, but need to signal the middleware that the bank is not responding with 500 Internal Server Error. Used for example when a client is trying to register with a unavailable username.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- BANK_SOFT_EXCEPTION = 5400,
-
- /**
- * The request UID for a request to transfer funds has already been used, but with different details for the transfer.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- BANK_TRANSFER_REQUEST_UID_REUSED = 5500,
-
- /**
- * The sync service failed to access its database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_DB_FETCH_ERROR = 6000,
-
- /**
- * The sync service failed find the record in its database.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_BACKUP_UNKNOWN = 6001,
-
- /**
- * The sync service failed find the account in its database.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_ACCOUNT_UNKNOWN = 6002,
-
- /**
- * The SHA-512 hash provided in the If-None-Match header is malformed.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_BAD_IF_NONE_MATCH = 6003,
-
- /**
- * The SHA-512 hash provided in the If-Match header is malformed or missing.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_BAD_IF_MATCH = 6004,
-
- /**
- * The signature provided in the "Sync-Signature" header is malformed or missing.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_BAD_SYNC_SIGNATURE = 6005,
-
- /**
- * The signature provided in the "Sync-Signature" header does not match the account, old or new Etags.
- * Returned with an HTTP status code of #MHD_HTTP_FORBIDDEN (403).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_INVALID_SIGNATURE = 6007,
-
- /**
- * The "Content-length" field for the upload is either not a number, or too big, or missing.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_BAD_CONTENT_LENGTH = 6008,
-
- /**
- * The "Content-length" field for the upload is too big based on the server's terms of service.
- * Returned with an HTTP status code of #MHD_HTTP_PAYLOAD_TOO_LARGE (413).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_EXCESSIVE_CONTENT_LENGTH = 6009,
-
- /**
- * The server is out of memory to handle the upload. Trying again later may succeed.
- * Returned with an HTTP status code of #MHD_HTTP_PAYLOAD_TOO_LARGE (413).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_OUT_OF_MEMORY_ON_CONTENT_LENGTH = 6010,
-
- /**
- * The uploaded data does not match the Etag.
- * Returned with an HTTP status code of #MHD_HTTP_BAD_REQUEST (400).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_INVALID_UPLOAD = 6011,
-
- /**
- * We failed to check for existing upload data in the database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_DATABASE_FETCH_ERROR = 6012,
-
- /**
- * HTTP server was being shutdown while this operation was pending.
- * Returned with an HTTP status code of #MHD_HTTP_SERVICE_UNAVAILABLE (503).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_SHUTDOWN = 6013,
-
- /**
- * HTTP server experienced a timeout while awaiting promised payment.
- * Returned with an HTTP status code of #MHD_HTTP_REQUEST_TIMEOUT (408).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_PAYMENT_TIMEOUT = 6014,
-
- /**
- * Sync could not store order data in its own database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_PAYMENT_CREATE_DB_ERROR = 6015,
-
- /**
- * Sync could not store payment confirmation in its own database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_PAYMENT_CONFIRM_DB_ERROR = 6016,
-
- /**
- * Sync could not fetch information about possible existing orders from its own database.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_PAYMENT_CHECK_ORDER_DB_ERROR = 6017,
-
- /**
- * Sync could not setup the payment request with its own backend.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_PAYMENT_CREATE_BACKEND_ERROR = 6018,
-
- /**
- * The sync service failed find the backup to be updated in its database.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- SYNC_PREVIOUS_BACKUP_UNKNOWN = 6019,
-
- /**
- * The wallet does not implement a version of the exchange protocol that is compatible with the protocol version of the exchange.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_IMPLEMENTED (501).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WALLET_EXCHANGE_PROTOCOL_VERSION_INCOMPATIBLE = 7000,
-
- /**
- * The wallet encountered an unexpected exception. This is likely a bug in the wallet implementation.
- * Returned with an HTTP status code of #MHD_HTTP_INTERNAL_SERVER_ERROR (500).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WALLET_UNEXPECTED_EXCEPTION = 7001,
-
- /**
- * The wallet received a response from a server, but the response can't be parsed.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WALLET_RECEIVED_MALFORMED_RESPONSE = 7002,
-
- /**
- * The wallet tried to make a network request, but it received no response.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WALLET_NETWORK_ERROR = 7003,
-
- /**
- * The wallet tried to make a network request, but it was throttled.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WALLET_HTTP_REQUEST_THROTTLED = 7004,
-
- /**
- * The wallet made a request to a service, but received an error response it does not know how to handle.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WALLET_UNEXPECTED_REQUEST_ERROR = 7005,
-
- /**
- * The denominations offered by the exchange are insufficient. Likely the exchange is badly configured or not maintained.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WALLET_EXCHANGE_DENOMINATIONS_INSUFFICIENT = 7006,
-
- /**
- * The wallet does not support the operation requested by a client.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WALLET_CORE_API_OPERATION_UNKNOWN = 7007,
-
- /**
- * The given taler://pay URI is invalid.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WALLET_INVALID_TALER_PAY_URI = 7008,
-
- /**
- * The exchange does not know about the reserve (yet), and thus withdrawal can't progress.
- * Returned with an HTTP status code of #MHD_HTTP_NOT_FOUND (404).
- * (A value of 0 indicates that the error is generated client-side).
- */
- WALLET_WITHDRAW_RESERVE_UNKNOWN_AT_EXCHANGE = 7010,
-
- /**
- * End of error code range.
- * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0).
- * (A value of 0 indicates that the error is generated client-side).
- */
- END = 9999,
-
-}
diff --git a/src/android/index.ts b/src/android/index.ts
deleted file mode 100644
index 389a081b7..000000000
--- a/src/android/index.ts
+++ /dev/null
@@ -1,287 +0,0 @@
-/*
- 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/>
- */
-
-/**
- * Imports.
- */
-import { Wallet } from "../wallet";
-import {
- getDefaultNodeWallet,
- DefaultNodeWalletArgs,
-} from "../headless/helpers";
-import { openPromise, OpenedPromise } from "../util/promiseUtils";
-import fs from "fs";
-import {
- HttpRequestLibrary,
- HttpResponse,
- HttpRequestOptions,
- Headers,
-} from "../util/http";
-import { NodeHttpLib } from "../headless/NodeHttpLib";
-import { WalletNotification } from "../types/notifications";
-import {
- WALLET_EXCHANGE_PROTOCOL_VERSION,
- WALLET_MERCHANT_PROTOCOL_VERSION,
-} from "../operations/versions";
-import {
- handleCoreApiRequest,
- CoreApiResponseSuccess,
- CoreApiResponse,
- CoreApiEnvelope,
-} from "../walletCoreApiHandler";
-import { makeErrorDetails } from "../operations/errors";
-import { TalerErrorCode } from "../TalerErrorCode";
-
-// @ts-ignore: special built-in module
-//import akono = require("akono");
-
-export {
- handleWorkerError,
- handleWorkerMessage,
-} from "../crypto/workers/nodeThreadWorker";
-
-export class AndroidHttpLib implements HttpRequestLibrary {
- useNfcTunnel = false;
-
- private nodeHttpLib: HttpRequestLibrary = new NodeHttpLib();
-
- private requestId = 1;
-
- private requestMap: { [id: number]: OpenedPromise<HttpResponse> } = {};
-
- constructor(private sendMessage: (m: string) => void) {}
-
- get(url: string, opt?: HttpRequestOptions): Promise<HttpResponse> {
- if (this.useNfcTunnel) {
- const myId = this.requestId++;
- const p = openPromise<HttpResponse>();
- this.requestMap[myId] = p;
- const request = {
- method: "get",
- url,
- };
- this.sendMessage(
- JSON.stringify({
- type: "tunnelHttp",
- request,
- id: myId,
- }),
- );
- return p.promise;
- } else {
- return this.nodeHttpLib.get(url, opt);
- }
- }
-
- postJson(
- url: string,
- body: any,
- opt?: HttpRequestOptions,
- ): Promise<import("../util/http").HttpResponse> {
- if (this.useNfcTunnel) {
- const myId = this.requestId++;
- const p = openPromise<HttpResponse>();
- this.requestMap[myId] = p;
- const request = {
- method: "postJson",
- url,
- body,
- };
- this.sendMessage(
- JSON.stringify({ type: "tunnelHttp", request, id: myId }),
- );
- return p.promise;
- } else {
- return this.nodeHttpLib.postJson(url, body, opt);
- }
- }
-
- handleTunnelResponse(msg: any): void {
- const myId = msg.id;
- const p = this.requestMap[myId];
- if (!p) {
- console.error(
- `no matching request for tunneled HTTP response, id=${myId}`,
- );
- }
- const headers = new Headers();
- if (msg.status != 0) {
- const resp: HttpResponse = {
- // FIXME: pass through this URL
- requestUrl: "",
- headers,
- status: msg.status,
- json: async () => JSON.parse(msg.responseText),
- text: async () => msg.responseText,
- };
- p.resolve(resp);
- } else {
- p.reject(new Error(`unexpected HTTP status code ${msg.status}`));
- }
- delete this.requestMap[myId];
- }
-}
-
-function sendAkonoMessage(ev: CoreApiEnvelope): void {
- // @ts-ignore
- const sendMessage = globalThis.__akono_sendMessage;
- if (typeof sendMessage !== "function") {
- const errMsg =
- "FATAL: cannot install android wallet listener: akono functions missing";
- console.error(errMsg);
- throw new Error(errMsg);
- }
- const m = JSON.stringify(ev);
- // @ts-ignore
- sendMessage(m);
-}
-
-class AndroidWalletMessageHandler {
- walletArgs: DefaultNodeWalletArgs | undefined;
- maybeWallet: Wallet | undefined;
- wp = openPromise<Wallet>();
- httpLib = new NodeHttpLib();
-
- /**
- * Handle a request from the Android wallet.
- */
- async handleMessage(
- operation: string,
- id: string,
- args: any,
- ): Promise<CoreApiResponse> {
- const wrapResponse = (result: unknown): CoreApiResponseSuccess => {
- return {
- type: "response",
- id,
- operation,
- result,
- };
- };
- switch (operation) {
- case "init": {
- this.walletArgs = {
- notifyHandler: async (notification: WalletNotification) => {
- sendAkonoMessage({ type: "notification", payload: notification });
- },
- persistentStoragePath: args.persistentStoragePath,
- httpLib: this.httpLib,
- };
- const w = await getDefaultNodeWallet(this.walletArgs);
- this.maybeWallet = w;
- w.runRetryLoop().catch((e) => {
- console.error("Error during wallet retry loop", e);
- });
- this.wp.resolve(w);
- return wrapResponse({
- supported_protocol_versions: {
- exchange: WALLET_EXCHANGE_PROTOCOL_VERSION,
- merchant: WALLET_MERCHANT_PROTOCOL_VERSION,
- },
- });
- }
- case "getHistory": {
- return wrapResponse({ history: [] });
- }
- case "startTunnel": {
- // this.httpLib.useNfcTunnel = true;
- throw Error("not implemented");
- }
- case "stopTunnel": {
- // this.httpLib.useNfcTunnel = false;
- throw Error("not implemented");
- }
- case "tunnelResponse": {
- // httpLib.handleTunnelResponse(msg.args);
- throw Error("not implemented");
- }
- case "reset": {
- const oldArgs = this.walletArgs;
- this.walletArgs = { ...oldArgs };
- if (oldArgs && oldArgs.persistentStoragePath) {
- try {
- fs.unlinkSync(oldArgs.persistentStoragePath);
- } catch (e) {
- console.error("Error while deleting the wallet db:", e);
- }
- // Prevent further storage!
- this.walletArgs.persistentStoragePath = undefined;
- }
- const wallet = await this.wp.promise;
- wallet.stop();
- this.wp = openPromise<Wallet>();
- this.maybeWallet = undefined;
- const w = await getDefaultNodeWallet(this.walletArgs);
- this.maybeWallet = w;
- w.runRetryLoop().catch((e) => {
- console.error("Error during wallet retry loop", e);
- });
- this.wp.resolve(w);
- return wrapResponse({});
- }
- default: {
- const wallet = await this.wp.promise;
- return await handleCoreApiRequest(wallet, operation, id, args);
- }
- }
- }
-}
-
-export function installAndroidWalletListener(): void {
- const handler = new AndroidWalletMessageHandler();
- const onMessage = async (msgStr: any): Promise<void> => {
- if (typeof msgStr !== "string") {
- console.error("expected string as message");
- return;
- }
- const msg = JSON.parse(msgStr);
- const operation = msg.operation;
- if (typeof operation !== "string") {
- console.error(
- "message to android wallet helper must contain operation of type string",
- );
- return;
- }
- const id = msg.id;
- console.log(`android listener: got request for ${operation} (${id})`);
-
- try {
- const respMsg = await handler.handleMessage(operation, id, msg.args);
- console.log(
- `android listener: sending success response for ${operation} (${id})`,
- );
- sendAkonoMessage(respMsg);
- } catch (e) {
- const respMsg: CoreApiResponse = {
- type: "error",
- id,
- operation,
- error: makeErrorDetails(
- TalerErrorCode.WALLET_UNEXPECTED_EXCEPTION,
- "unexpected exception",
- {},
- ),
- };
- sendAkonoMessage(respMsg);
- return;
- }
- };
-
- // @ts-ignore
- globalThis.__akono_onMessage = onMessage;
-
- console.log("android wallet listener installed");
-}
diff --git a/src/crypto/primitives/kdf.ts b/src/crypto/primitives/kdf.ts
deleted file mode 100644
index edc681bc1..000000000
--- a/src/crypto/primitives/kdf.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- 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 * as nacl from "./nacl-fast";
-import { sha256 } from "./sha256";
-
-export function sha512(data: Uint8Array): Uint8Array {
- return nacl.hash(data);
-}
-
-export function hmac(
- digest: (d: Uint8Array) => Uint8Array,
- blockSize: number,
- key: Uint8Array,
- message: Uint8Array,
-): Uint8Array {
- if (key.byteLength > blockSize) {
- key = digest(key);
- }
- if (key.byteLength < blockSize) {
- const k = key;
- key = new Uint8Array(blockSize);
- key.set(k, 0);
- }
- const okp = new Uint8Array(blockSize);
- const ikp = new Uint8Array(blockSize);
- for (let i = 0; i < blockSize; i++) {
- ikp[i] = key[i] ^ 0x36;
- okp[i] = key[i] ^ 0x5c;
- }
- const b1 = new Uint8Array(blockSize + message.byteLength);
- b1.set(ikp, 0);
- b1.set(message, blockSize);
- const h0 = digest(b1);
- const b2 = new Uint8Array(blockSize + h0.length);
- b2.set(okp, 0);
- b2.set(h0, blockSize);
- return digest(b2);
-}
-
-export function hmacSha512(key: Uint8Array, message: Uint8Array): Uint8Array {
- return hmac(sha512, 128, key, message);
-}
-
-export function hmacSha256(key: Uint8Array, message: Uint8Array): Uint8Array {
- return hmac(sha256, 64, key, message);
-}
-
-export function kdf(
- outputLength: number,
- ikm: Uint8Array,
- salt: Uint8Array,
- info: Uint8Array,
-): Uint8Array {
- // extract
- const prk = hmacSha512(salt, ikm);
-
- // expand
- const N = Math.ceil(outputLength / 32);
- const output = new Uint8Array(N * 32);
- for (let i = 0; i < N; i++) {
- let buf;
- if (i == 0) {
- buf = new Uint8Array(info.byteLength + 1);
- buf.set(info, 0);
- } else {
- buf = new Uint8Array(info.byteLength + 1 + 32);
- for (let j = 0; j < 32; j++) {
- buf[j] = output[(i - 1) * 32 + j];
- }
- buf.set(info, 32);
- }
- buf[buf.length - 1] = i + 1;
- const chunk = hmacSha256(prk, buf);
- output.set(chunk, i * 32);
- }
-
- return output.slice(0, outputLength);
-}
diff --git a/src/crypto/primitives/nacl-fast.ts b/src/crypto/primitives/nacl-fast.ts
deleted file mode 100644
index 8d4aaeb63..000000000
--- a/src/crypto/primitives/nacl-fast.ts
+++ /dev/null
@@ -1,1941 +0,0 @@
-// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
-// TypeScript port in 2019 by Florian Dold.
-// Public domain.
-//
-// Implementation derived from TweetNaCl version 20140427.
-// See for details: http://tweetnacl.cr.yp.to/
-
-const gf = function (init: number[] = []): Float64Array {
- const r = new Float64Array(16);
- if (init) for (let i = 0; i < init.length; i++) r[i] = init[i];
- return r;
-};
-
-// Pluggable, initialized in high-level API below.
-let randombytes = function (x: Uint8Array, n: number): void {
- throw new Error("no PRNG");
-};
-
-const _9 = new Uint8Array(32);
-_9[0] = 9;
-
-// prettier-ignore
-const gf0 = gf();
-const gf1 = gf([1]);
-const _121665 = gf([0xdb41, 1]);
-const D = gf([
- 0x78a3,
- 0x1359,
- 0x4dca,
- 0x75eb,
- 0xd8ab,
- 0x4141,
- 0x0a4d,
- 0x0070,
- 0xe898,
- 0x7779,
- 0x4079,
- 0x8cc7,
- 0xfe73,
- 0x2b6f,
- 0x6cee,
- 0x5203,
-]);
-const D2 = gf([
- 0xf159,
- 0x26b2,
- 0x9b94,
- 0xebd6,
- 0xb156,
- 0x8283,
- 0x149a,
- 0x00e0,
- 0xd130,
- 0xeef3,
- 0x80f2,
- 0x198e,
- 0xfce7,
- 0x56df,
- 0xd9dc,
- 0x2406,
-]);
-const X = gf([
- 0xd51a,
- 0x8f25,
- 0x2d60,
- 0xc956,
- 0xa7b2,
- 0x9525,
- 0xc760,
- 0x692c,
- 0xdc5c,
- 0xfdd6,
- 0xe231,
- 0xc0a4,
- 0x53fe,
- 0xcd6e,
- 0x36d3,
- 0x2169,
-]);
-const Y = gf([
- 0x6658,
- 0x6666,
- 0x6666,
- 0x6666,
- 0x6666,
- 0x6666,
- 0x6666,
- 0x6666,
- 0x6666,
- 0x6666,
- 0x6666,
- 0x6666,
- 0x6666,
- 0x6666,
- 0x6666,
- 0x6666,
-]);
-const I = gf([
- 0xa0b0,
- 0x4a0e,
- 0x1b27,
- 0xc4ee,
- 0xe478,
- 0xad2f,
- 0x1806,
- 0x2f43,
- 0xd7a7,
- 0x3dfb,
- 0x0099,
- 0x2b4d,
- 0xdf0b,
- 0x4fc1,
- 0x2480,
- 0x2b83,
-]);
-
-function ts64(x: Uint8Array, i: number, h: number, l: number): void {
- x[i] = (h >> 24) & 0xff;
- x[i + 1] = (h >> 16) & 0xff;
- x[i + 2] = (h >> 8) & 0xff;
- x[i + 3] = h & 0xff;
- x[i + 4] = (l >> 24) & 0xff;
- x[i + 5] = (l >> 16) & 0xff;
- x[i + 6] = (l >> 8) & 0xff;
- x[i + 7] = l & 0xff;
-}
-
-function vn(
- x: Uint8Array,
- xi: number,
- y: Uint8Array,
- yi: number,
- n: number,
-): number {
- let i,
- d = 0;
- for (i = 0; i < n; i++) d |= x[xi + i] ^ y[yi + i];
- return (1 & ((d - 1) >>> 8)) - 1;
-}
-
-function crypto_verify_32(
- x: Uint8Array,
- xi: number,
- y: Uint8Array,
- yi: number,
-): number {
- return vn(x, xi, y, yi, 32);
-}
-
-function set25519(r: Float64Array, a: Float64Array): void {
- let i;
- for (i = 0; i < 16; i++) r[i] = a[i] | 0;
-}
-
-function car25519(o: Float64Array): void {
- let i,
- v,
- c = 1;
- for (i = 0; i < 16; i++) {
- v = o[i] + c + 65535;
- c = Math.floor(v / 65536);
- o[i] = v - c * 65536;
- }
- o[0] += c - 1 + 37 * (c - 1);
-}
-
-function sel25519(p: Float64Array, q: Float64Array, b: number): void {
- let t;
- const c = ~(b - 1);
- for (let i = 0; i < 16; i++) {
- t = c & (p[i] ^ q[i]);
- p[i] ^= t;
- q[i] ^= t;
- }
-}
-
-function pack25519(o: Uint8Array, n: Float64Array): void {
- let i, j, b;
- const m = gf(),
- t = gf();
- for (i = 0; i < 16; i++) t[i] = n[i];
- car25519(t);
- car25519(t);
- car25519(t);
- for (j = 0; j < 2; j++) {
- m[0] = t[0] - 0xffed;
- for (i = 1; i < 15; i++) {
- m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);
- m[i - 1] &= 0xffff;
- }
- m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);
- b = (m[15] >> 16) & 1;
- m[14] &= 0xffff;
- sel25519(t, m, 1 - b);
- }
- for (i = 0; i < 16; i++) {
- o[2 * i] = t[i] & 0xff;
- o[2 * i + 1] = t[i] >> 8;
- }
-}
-
-function neq25519(a: Float64Array, b: Float64Array): number {
- const c = new Uint8Array(32),
- d = new Uint8Array(32);
- pack25519(c, a);
- pack25519(d, b);
- return crypto_verify_32(c, 0, d, 0);
-}
-
-function par25519(a: Float64Array): number {
- const d = new Uint8Array(32);
- pack25519(d, a);
- return d[0] & 1;
-}
-
-function unpack25519(o: Float64Array, n: Uint8Array): void {
- let i;
- for (i = 0; i < 16; i++) o[i] = n[2 * i] + (n[2 * i + 1] << 8);
- o[15] &= 0x7fff;
-}
-
-function A(o: Float64Array, a: Float64Array, b: Float64Array): void {
- for (let i = 0; i < 16; i++) o[i] = a[i] + b[i];
-}
-
-function Z(o: Float64Array, a: Float64Array, b: Float64Array): void {
- for (let i = 0; i < 16; i++) o[i] = a[i] - b[i];
-}
-
-function M(o: Float64Array, a: Float64Array, b: Float64Array): void {
- let v,
- c,
- t0 = 0,
- t1 = 0,
- t2 = 0,
- t3 = 0,
- t4 = 0,
- t5 = 0,
- t6 = 0,
- t7 = 0,
- t8 = 0,
- t9 = 0,
- t10 = 0,
- t11 = 0,
- t12 = 0,
- t13 = 0,
- t14 = 0,
- t15 = 0,
- t16 = 0,
- t17 = 0,
- t18 = 0,
- t19 = 0,
- t20 = 0,
- t21 = 0,
- t22 = 0,
- t23 = 0,
- t24 = 0,
- t25 = 0,
- t26 = 0,
- t27 = 0,
- t28 = 0,
- t29 = 0,
- t30 = 0;
- const b0 = b[0],
- b1 = b[1],
- b2 = b[2],
- b3 = b[3],
- b4 = b[4],
- b5 = b[5],
- b6 = b[6],
- b7 = b[7],
- b8 = b[8],
- b9 = b[9],
- b10 = b[10],
- b11 = b[11],
- b12 = b[12],
- b13 = b[13],
- b14 = b[14],
- b15 = b[15];
-
- v = a[0];
- t0 += v * b0;
- t1 += v * b1;
- t2 += v * b2;
- t3 += v * b3;
- t4 += v * b4;
- t5 += v * b5;
- t6 += v * b6;
- t7 += v * b7;
- t8 += v * b8;
- t9 += v * b9;
- t10 += v * b10;
- t11 += v * b11;
- t12 += v * b12;
- t13 += v * b13;
- t14 += v * b14;
- t15 += v * b15;
- v = a[1];
- t1 += v * b0;
- t2 += v * b1;
- t3 += v * b2;
- t4 += v * b3;
- t5 += v * b4;
- t6 += v * b5;
- t7 += v * b6;
- t8 += v * b7;
- t9 += v * b8;
- t10 += v * b9;
- t11 += v * b10;
- t12 += v * b11;
- t13 += v * b12;
- t14 += v * b13;
- t15 += v * b14;
- t16 += v * b15;
- v = a[2];
- t2 += v * b0;
- t3 += v * b1;
- t4 += v * b2;
- t5 += v * b3;
- t6 += v * b4;
- t7 += v * b5;
- t8 += v * b6;
- t9 += v * b7;
- t10 += v * b8;
- t11 += v * b9;
- t12 += v * b10;
- t13 += v * b11;
- t14 += v * b12;
- t15 += v * b13;
- t16 += v * b14;
- t17 += v * b15;
- v = a[3];
- t3 += v * b0;
- t4 += v * b1;
- t5 += v * b2;
- t6 += v * b3;
- t7 += v * b4;
- t8 += v * b5;
- t9 += v * b6;
- t10 += v * b7;
- t11 += v * b8;
- t12 += v * b9;
- t13 += v * b10;
- t14 += v * b11;
- t15 += v * b12;
- t16 += v * b13;
- t17 += v * b14;
- t18 += v * b15;
- v = a[4];
- t4 += v * b0;
- t5 += v * b1;
- t6 += v * b2;
- t7 += v * b3;
- t8 += v * b4;
- t9 += v * b5;
- t10 += v * b6;
- t11 += v * b7;
- t12 += v * b8;
- t13 += v * b9;
- t14 += v * b10;
- t15 += v * b11;
- t16 += v * b12;
- t17 += v * b13;
- t18 += v * b14;
- t19 += v * b15;
- v = a[5];
- t5 += v * b0;
- t6 += v * b1;
- t7 += v * b2;
- t8 += v * b3;
- t9 += v * b4;
- t10 += v * b5;
- t11 += v * b6;
- t12 += v * b7;
- t13 += v * b8;
- t14 += v * b9;
- t15 += v * b10;
- t16 += v * b11;
- t17 += v * b12;
- t18 += v * b13;
- t19 += v * b14;
- t20 += v * b15;
- v = a[6];
- t6 += v * b0;
- t7 += v * b1;
- t8 += v * b2;
- t9 += v * b3;
- t10 += v * b4;
- t11 += v * b5;
- t12 += v * b6;
- t13 += v * b7;
- t14 += v * b8;
- t15 += v * b9;
- t16 += v * b10;
- t17 += v * b11;
- t18 += v * b12;
- t19 += v * b13;
- t20 += v * b14;
- t21 += v * b15;
- v = a[7];
- t7 += v * b0;
- t8 += v * b1;
- t9 += v * b2;
- t10 += v * b3;
- t11 += v * b4;
- t12 += v * b5;
- t13 += v * b6;
- t14 += v * b7;
- t15 += v * b8;
- t16 += v * b9;
- t17 += v * b10;
- t18 += v * b11;
- t19 += v * b12;
- t20 += v * b13;
- t21 += v * b14;
- t22 += v * b15;
- v = a[8];
- t8 += v * b0;
- t9 += v * b1;
- t10 += v * b2;
- t11 += v * b3;
- t12 += v * b4;
- t13 += v * b5;
- t14 += v * b6;
- t15 += v * b7;
- t16 += v * b8;
- t17 += v * b9;
- t18 += v * b10;
- t19 += v * b11;
- t20 += v * b12;
- t21 += v * b13;
- t22 += v * b14;
- t23 += v * b15;
- v = a[9];
- t9 += v * b0;
- t10 += v * b1;
- t11 += v * b2;
- t12 += v * b3;
- t13 += v * b4;
- t14 += v * b5;
- t15 += v * b6;
- t16 += v * b7;
- t17 += v * b8;
- t18 += v * b9;
- t19 += v * b10;
- t20 += v * b11;
- t21 += v * b12;
- t22 += v * b13;
- t23 += v * b14;
- t24 += v * b15;
- v = a[10];
- t10 += v * b0;
- t11 += v * b1;
- t12 += v * b2;
- t13 += v * b3;
- t14 += v * b4;
- t15 += v * b5;
- t16 += v * b6;
- t17 += v * b7;
- t18 += v * b8;
- t19 += v * b9;
- t20 += v * b10;
- t21 += v * b11;
- t22 += v * b12;
- t23 += v * b13;
- t24 += v * b14;
- t25 += v * b15;
- v = a[11];
- t11 += v * b0;
- t12 += v * b1;
- t13 += v * b2;
- t14 += v * b3;
- t15 += v * b4;
- t16 += v * b5;
- t17 += v * b6;
- t18 += v * b7;
- t19 += v * b8;
- t20 += v * b9;
- t21 += v * b10;
- t22 += v * b11;
- t23 += v * b12;
- t24 += v * b13;
- t25 += v * b14;
- t26 += v * b15;
- v = a[12];
- t12 += v * b0;
- t13 += v * b1;
- t14 += v * b2;
- t15 += v * b3;
- t16 += v * b4;
- t17 += v * b5;
- t18 += v * b6;
- t19 += v * b7;
- t20 += v * b8;
- t21 += v * b9;
- t22 += v * b10;
- t23 += v * b11;
- t24 += v * b12;
- t25 += v * b13;
- t26 += v * b14;
- t27 += v * b15;
- v = a[13];
- t13 += v * b0;
- t14 += v * b1;
- t15 += v * b2;
- t16 += v * b3;
- t17 += v * b4;
- t18 += v * b5;
- t19 += v * b6;
- t20 += v * b7;
- t21 += v * b8;
- t22 += v * b9;
- t23 += v * b10;
- t24 += v * b11;
- t25 += v * b12;
- t26 += v * b13;
- t27 += v * b14;
- t28 += v * b15;
- v = a[14];
- t14 += v * b0;
- t15 += v * b1;
- t16 += v * b2;
- t17 += v * b3;
- t18 += v * b4;
- t19 += v * b5;
- t20 += v * b6;
- t21 += v * b7;
- t22 += v * b8;
- t23 += v * b9;
- t24 += v * b10;
- t25 += v * b11;
- t26 += v * b12;
- t27 += v * b13;
- t28 += v * b14;
- t29 += v * b15;
- v = a[15];
- t15 += v * b0;
- t16 += v * b1;
- t17 += v * b2;
- t18 += v * b3;
- t19 += v * b4;
- t20 += v * b5;
- t21 += v * b6;
- t22 += v * b7;
- t23 += v * b8;
- t24 += v * b9;
- t25 += v * b10;
- t26 += v * b11;
- t27 += v * b12;
- t28 += v * b13;
- t29 += v * b14;
- t30 += v * b15;
-
- t0 += 38 * t16;
- t1 += 38 * t17;
- t2 += 38 * t18;
- t3 += 38 * t19;
- t4 += 38 * t20;
- t5 += 38 * t21;
- t6 += 38 * t22;
- t7 += 38 * t23;
- t8 += 38 * t24;
- t9 += 38 * t25;
- t10 += 38 * t26;
- t11 += 38 * t27;
- t12 += 38 * t28;
- t13 += 38 * t29;
- t14 += 38 * t30;
- // t15 left as is
-
- // first car
- c = 1;
- v = t0 + c + 65535;
- c = Math.floor(v / 65536);
- t0 = v - c * 65536;
- v = t1 + c + 65535;
- c = Math.floor(v / 65536);
- t1 = v - c * 65536;
- v = t2 + c + 65535;
- c = Math.floor(v / 65536);
- t2 = v - c * 65536;
- v = t3 + c + 65535;
- c = Math.floor(v / 65536);
- t3 = v - c * 65536;
- v = t4 + c + 65535;
- c = Math.floor(v / 65536);
- t4 = v - c * 65536;
- v = t5 + c + 65535;
- c = Math.floor(v / 65536);
- t5 = v - c * 65536;
- v = t6 + c + 65535;
- c = Math.floor(v / 65536);
- t6 = v - c * 65536;
- v = t7 + c + 65535;
- c = Math.floor(v / 65536);
- t7 = v - c * 65536;
- v = t8 + c + 65535;
- c = Math.floor(v / 65536);
- t8 = v - c * 65536;
- v = t9 + c + 65535;
- c = Math.floor(v / 65536);
- t9 = v - c * 65536;
- v = t10 + c + 65535;
- c = Math.floor(v / 65536);
- t10 = v - c * 65536;
- v = t11 + c + 65535;
- c = Math.floor(v / 65536);
- t11 = v - c * 65536;
- v = t12 + c + 65535;
- c = Math.floor(v / 65536);
- t12 = v - c * 65536;
- v = t13 + c + 65535;
- c = Math.floor(v / 65536);
- t13 = v - c * 65536;
- v = t14 + c + 65535;
- c = Math.floor(v / 65536);
- t14 = v - c * 65536;
- v = t15 + c + 65535;
- c = Math.floor(v / 65536);
- t15 = v - c * 65536;
- t0 += c - 1 + 37 * (c - 1);
-
- // second car
- c = 1;
- v = t0 + c + 65535;
- c = Math.floor(v / 65536);
- t0 = v - c * 65536;
- v = t1 + c + 65535;
- c = Math.floor(v / 65536);
- t1 = v - c * 65536;
- v = t2 + c + 65535;
- c = Math.floor(v / 65536);
- t2 = v - c * 65536;
- v = t3 + c + 65535;
- c = Math.floor(v / 65536);
- t3 = v - c * 65536;
- v = t4 + c + 65535;
- c = Math.floor(v / 65536);
- t4 = v - c * 65536;
- v = t5 + c + 65535;
- c = Math.floor(v / 65536);
- t5 = v - c * 65536;
- v = t6 + c + 65535;
- c = Math.floor(v / 65536);
- t6 = v - c * 65536;
- v = t7 + c + 65535;
- c = Math.floor(v / 65536);
- t7 = v - c * 65536;
- v = t8 + c + 65535;
- c = Math.floor(v / 65536);
- t8 = v - c * 65536;
- v = t9 + c + 65535;
- c = Math.floor(v / 65536);
- t9 = v - c * 65536;
- v = t10 + c + 65535;
- c = Math.floor(v / 65536);
- t10 = v - c * 65536;
- v = t11 + c + 65535;
- c = Math.floor(v / 65536);
- t11 = v - c * 65536;
- v = t12 + c + 65535;
- c = Math.floor(v / 65536);
- t12 = v - c * 65536;
- v = t13 + c + 65535;
- c = Math.floor(v / 65536);
- t13 = v - c * 65536;
- v = t14 + c + 65535;
- c = Math.floor(v / 65536);
- t14 = v - c * 65536;
- v = t15 + c + 65535;
- c = Math.floor(v / 65536);
- t15 = v - c * 65536;
- t0 += c - 1 + 37 * (c - 1);
-
- o[0] = t0;
- o[1] = t1;
- o[2] = t2;
- o[3] = t3;
- o[4] = t4;
- o[5] = t5;
- o[6] = t6;
- o[7] = t7;
- o[8] = t8;
- o[9] = t9;
- o[10] = t10;
- o[11] = t11;
- o[12] = t12;
- o[13] = t13;
- o[14] = t14;
- o[15] = t15;
-}
-
-function S(o: Float64Array, a: Float64Array): void {
- M(o, a, a);
-}
-
-function inv25519(o: Float64Array, i: Float64Array): void {
- const c = gf();
- let a;
- for (a = 0; a < 16; a++) c[a] = i[a];
- for (a = 253; a >= 0; a--) {
- S(c, c);
- if (a !== 2 && a !== 4) M(c, c, i);
- }
- for (a = 0; a < 16; a++) o[a] = c[a];
-}
-
-function pow2523(o: Float64Array, i: Float64Array): void {
- const c = gf();
- let a;
- for (a = 0; a < 16; a++) c[a] = i[a];
- for (a = 250; a >= 0; a--) {
- S(c, c);
- if (a !== 1) M(c, c, i);
- }
- for (a = 0; a < 16; a++) o[a] = c[a];
-}
-
-function crypto_scalarmult(
- q: Uint8Array,
- n: Uint8Array,
- p: Uint8Array,
-): number {
- const z = new Uint8Array(32);
- const x = new Float64Array(80);
- let r;
- let i;
- const a = gf(),
- b = gf(),
- c = gf(),
- d = gf(),
- e = gf(),
- f = gf();
- for (i = 0; i < 31; i++) z[i] = n[i];
- z[31] = (n[31] & 127) | 64;
- z[0] &= 248;
- unpack25519(x, p);
- for (i = 0; i < 16; i++) {
- b[i] = x[i];
- d[i] = a[i] = c[i] = 0;
- }
- a[0] = d[0] = 1;
- for (i = 254; i >= 0; --i) {
- r = (z[i >>> 3] >>> (i & 7)) & 1;
- sel25519(a, b, r);
- sel25519(c, d, r);
- A(e, a, c);
- Z(a, a, c);
- A(c, b, d);
- Z(b, b, d);
- S(d, e);
- S(f, a);
- M(a, c, a);
- M(c, b, e);
- A(e, a, c);
- Z(a, a, c);
- S(b, a);
- Z(c, d, f);
- M(a, c, _121665);
- A(a, a, d);
- M(c, c, a);
- M(a, d, f);
- M(d, b, x);
- S(b, e);
- sel25519(a, b, r);
- sel25519(c, d, r);
- }
- for (i = 0; i < 16; i++) {
- x[i + 16] = a[i];
- x[i + 32] = c[i];
- x[i + 48] = b[i];
- x[i + 64] = d[i];
- }
- const x32 = x.subarray(32);
- const x16 = x.subarray(16);
- inv25519(x32, x32);
- M(x16, x16, x32);
- pack25519(q, x16);
- return 0;
-}
-
-function crypto_scalarmult_base(q: Uint8Array, n: Uint8Array): number {
- return crypto_scalarmult(q, n, _9);
-}
-
-// prettier-ignore
-const K = [
- 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
- 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
- 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
- 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
- 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
- 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
- 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
- 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
- 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
- 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
- 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
- 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
- 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
- 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
- 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
- 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
- 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
- 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
- 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
- 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
- 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
- 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
- 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
- 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
- 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
- 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
- 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
- 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
- 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
- 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
- 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
- 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
- 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
- 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
- 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
- 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
- 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
- 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
- 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
- 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
-];
-
-function crypto_hashblocks_hl(
- hh: Int32Array,
- hl: Int32Array,
- m: Uint8Array,
- n: number,
-): number {
- const wh = new Int32Array(16),
- wl = new Int32Array(16);
- let bh0,
- bh1,
- bh2,
- bh3,
- bh4,
- bh5,
- bh6,
- bh7,
- bl0,
- bl1,
- bl2,
- bl3,
- bl4,
- bl5,
- bl6,
- bl7,
- th,
- tl,
- i,
- j,
- h,
- l,
- a,
- b,
- c,
- d;
-
- let ah0 = hh[0],
- ah1 = hh[1],
- ah2 = hh[2],
- ah3 = hh[3],
- ah4 = hh[4],
- ah5 = hh[5],
- ah6 = hh[6],
- ah7 = hh[7],
- al0 = hl[0],
- al1 = hl[1],
- al2 = hl[2],
- al3 = hl[3],
- al4 = hl[4],
- al5 = hl[5],
- al6 = hl[6],
- al7 = hl[7];
-
- let pos = 0;
- while (n >= 128) {
- for (i = 0; i < 16; i++) {
- j = 8 * i + pos;
- wh[i] = (m[j + 0] << 24) | (m[j + 1] << 16) | (m[j + 2] << 8) | m[j + 3];
- wl[i] = (m[j + 4] << 24) | (m[j + 5] << 16) | (m[j + 6] << 8) | m[j + 7];
- }
- for (i = 0; i < 80; i++) {
- bh0 = ah0;
- bh1 = ah1;
- bh2 = ah2;
- bh3 = ah3;
- bh4 = ah4;
- bh5 = ah5;
- bh6 = ah6;
- bh7 = ah7;
-
- bl0 = al0;
- bl1 = al1;
- bl2 = al2;
- bl3 = al3;
- bl4 = al4;
- bl5 = al5;
- bl6 = al6;
- bl7 = al7;
-
- // add
- h = ah7;
- l = al7;
-
- a = l & 0xffff;
- b = l >>> 16;
- c = h & 0xffff;
- d = h >>> 16;
-
- // Sigma1
- h =
- ((ah4 >>> 14) | (al4 << (32 - 14))) ^
- ((ah4 >>> 18) | (al4 << (32 - 18))) ^
- ((al4 >>> (41 - 32)) | (ah4 << (32 - (41 - 32))));
- l =
- ((al4 >>> 14) | (ah4 << (32 - 14))) ^
- ((al4 >>> 18) | (ah4 << (32 - 18))) ^
- ((ah4 >>> (41 - 32)) | (al4 << (32 - (41 - 32))));
-
- a += l & 0xffff;
- b += l >>> 16;
- c += h & 0xffff;
- d += h >>> 16;
-
- // Ch
- h = (ah4 & ah5) ^ (~ah4 & ah6);
- l = (al4 & al5) ^ (~al4 & al6);
-
- a += l & 0xffff;
- b += l >>> 16;
- c += h & 0xffff;
- d += h >>> 16;
-
- // K
- h = K[i * 2];
- l = K[i * 2 + 1];
-
- a += l & 0xffff;
- b += l >>> 16;
- c += h & 0xffff;
- d += h >>> 16;
-
- // w
- h = wh[i % 16];
- l = wl[i % 16];
-
- a += l & 0xffff;
- b += l >>> 16;
- c += h & 0xffff;
- d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- th = (c & 0xffff) | (d << 16);
- tl = (a & 0xffff) | (b << 16);
-
- // add
- h = th;
- l = tl;
-
- a = l & 0xffff;
- b = l >>> 16;
- c = h & 0xffff;
- d = h >>> 16;
-
- // Sigma0
- h =
- ((ah0 >>> 28) | (al0 << (32 - 28))) ^
- ((al0 >>> (34 - 32)) | (ah0 << (32 - (34 - 32)))) ^
- ((al0 >>> (39 - 32)) | (ah0 << (32 - (39 - 32))));
- l =
- ((al0 >>> 28) | (ah0 << (32 - 28))) ^
- ((ah0 >>> (34 - 32)) | (al0 << (32 - (34 - 32)))) ^
- ((ah0 >>> (39 - 32)) | (al0 << (32 - (39 - 32))));
-
- a += l & 0xffff;
- b += l >>> 16;
- c += h & 0xffff;
- d += h >>> 16;
-
- // Maj
- h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);
- l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);
-
- a += l & 0xffff;
- b += l >>> 16;
- c += h & 0xffff;
- d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- bh7 = (c & 0xffff) | (d << 16);
- bl7 = (a & 0xffff) | (b << 16);
-
- // add
- h = bh3;
- l = bl3;
-
- a = l & 0xffff;
- b = l >>> 16;
- c = h & 0xffff;
- d = h >>> 16;
-
- h = th;
- l = tl;
-
- a += l & 0xffff;
- b += l >>> 16;
- c += h & 0xffff;
- d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- bh3 = (c & 0xffff) | (d << 16);
- bl3 = (a & 0xffff) | (b << 16);
-
- ah1 = bh0;
- ah2 = bh1;
- ah3 = bh2;
- ah4 = bh3;
- ah5 = bh4;
- ah6 = bh5;
- ah7 = bh6;
- ah0 = bh7;
-
- al1 = bl0;
- al2 = bl1;
- al3 = bl2;
- al4 = bl3;
- al5 = bl4;
- al6 = bl5;
- al7 = bl6;
- al0 = bl7;
-
- if (i % 16 === 15) {
- for (j = 0; j < 16; j++) {
- // add
- h = wh[j];
- l = wl[j];
-
- a = l & 0xffff;
- b = l >>> 16;
- c = h & 0xffff;
- d = h >>> 16;
-
- h = wh[(j + 9) % 16];
- l = wl[(j + 9) % 16];
-
- a += l & 0xffff;
- b += l >>> 16;
- c += h & 0xffff;
- d += h >>> 16;
-
- // sigma0
- th = wh[(j + 1) % 16];
- tl = wl[(j + 1) % 16];
- h =
- ((th >>> 1) | (tl << (32 - 1))) ^
- ((th >>> 8) | (tl << (32 - 8))) ^
- (th >>> 7);
- l =
- ((tl >>> 1) | (th << (32 - 1))) ^
- ((tl >>> 8) | (th << (32 - 8))) ^
- ((tl >>> 7) | (th << (32 - 7)));
-
- a += l & 0xffff;
- b += l >>> 16;
- c += h & 0xffff;
- d += h >>> 16;
-
- // sigma1
- th = wh[(j + 14) % 16];
- tl = wl[(j + 14) % 16];
- h =
- ((th >>> 19) | (tl << (32 - 19))) ^
- ((tl >>> (61 - 32)) | (th << (32 - (61 - 32)))) ^
- (th >>> 6);
- l =
- ((tl >>> 19) | (th << (32 - 19))) ^
- ((th >>> (61 - 32)) | (tl << (32 - (61 - 32)))) ^
- ((tl >>> 6) | (th << (32 - 6)));
-
- a += l & 0xffff;
- b += l >>> 16;
- c += h & 0xffff;
- d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- wh[j] = (c & 0xffff) | (d << 16);
- wl[j] = (a & 0xffff) | (b << 16);
- }
- }
- }
-
- // add
- h = ah0;
- l = al0;
-
- a = l & 0xffff;
- b = l >>> 16;
- c = h & 0xffff;
- d = h >>> 16;
-
- h = hh[0];
- l = hl[0];
-
- a += l & 0xffff;
- b += l >>> 16;
- c += h & 0xffff;
- d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- hh[0] = ah0 = (c & 0xffff) | (d << 16);
- hl[0] = al0 = (a & 0xffff) | (b << 16);
-
- h = ah1;
- l = al1;
-
- a = l & 0xffff;
- b = l >>> 16;
- c = h & 0xffff;
- d = h >>> 16;
-
- h = hh[1];
- l = hl[1];
-
- a += l & 0xffff;
- b += l >>> 16;
- c += h & 0xffff;
- d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- hh[1] = ah1 = (c & 0xffff) | (d << 16);
- hl[1] = al1 = (a & 0xffff) | (b << 16);
-
- h = ah2;
- l = al2;
-
- a = l & 0xffff;
- b = l >>> 16;
- c = h & 0xffff;
- d = h >>> 16;
-
- h = hh[2];
- l = hl[2];
-
- a += l & 0xffff;
- b += l >>> 16;
- c += h & 0xffff;
- d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- hh[2] = ah2 = (c & 0xffff) | (d << 16);
- hl[2] = al2 = (a & 0xffff) | (b << 16);
-
- h = ah3;
- l = al3;
-
- a = l & 0xffff;
- b = l >>> 16;
- c = h & 0xffff;
- d = h >>> 16;
-
- h = hh[3];
- l = hl[3];
-
- a += l & 0xffff;
- b += l >>> 16;
- c += h & 0xffff;
- d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- hh[3] = ah3 = (c & 0xffff) | (d << 16);
- hl[3] = al3 = (a & 0xffff) | (b << 16);
-
- h = ah4;
- l = al4;
-
- a = l & 0xffff;
- b = l >>> 16;
- c = h & 0xffff;
- d = h >>> 16;
-
- h = hh[4];
- l = hl[4];
-
- a += l & 0xffff;
- b += l >>> 16;
- c += h & 0xffff;
- d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- hh[4] = ah4 = (c & 0xffff) | (d << 16);
- hl[4] = al4 = (a & 0xffff) | (b << 16);
-
- h = ah5;
- l = al5;
-
- a = l & 0xffff;
- b = l >>> 16;
- c = h & 0xffff;
- d = h >>> 16;
-
- h = hh[5];
- l = hl[5];
-
- a += l & 0xffff;
- b += l >>> 16;
- c += h & 0xffff;
- d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- hh[5] = ah5 = (c & 0xffff) | (d << 16);
- hl[5] = al5 = (a & 0xffff) | (b << 16);
-
- h = ah6;
- l = al6;
-
- a = l & 0xffff;
- b = l >>> 16;
- c = h & 0xffff;
- d = h >>> 16;
-
- h = hh[6];
- l = hl[6];
-
- a += l & 0xffff;
- b += l >>> 16;
- c += h & 0xffff;
- d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- hh[6] = ah6 = (c & 0xffff) | (d << 16);
- hl[6] = al6 = (a & 0xffff) | (b << 16);
-
- h = ah7;
- l = al7;
-
- a = l & 0xffff;
- b = l >>> 16;
- c = h & 0xffff;
- d = h >>> 16;
-
- h = hh[7];
- l = hl[7];
-
- a += l & 0xffff;
- b += l >>> 16;
- c += h & 0xffff;
- d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- hh[7] = ah7 = (c & 0xffff) | (d << 16);
- hl[7] = al7 = (a & 0xffff) | (b << 16);
-
- pos += 128;
- n -= 128;
- }
-
- return n;
-}
-
-function crypto_hash(out: Uint8Array, m: Uint8Array, n: number): number {
- const hh = new Int32Array(8);
- const hl = new Int32Array(8);
- const x = new Uint8Array(256);
- const b = n;
-
- hh[0] = 0x6a09e667;
- hh[1] = 0xbb67ae85;
- hh[2] = 0x3c6ef372;
- hh[3] = 0xa54ff53a;
- hh[4] = 0x510e527f;
- hh[5] = 0x9b05688c;
- hh[6] = 0x1f83d9ab;
- hh[7] = 0x5be0cd19;
-
- hl[0] = 0xf3bcc908;
- hl[1] = 0x84caa73b;
- hl[2] = 0xfe94f82b;
- hl[3] = 0x5f1d36f1;
- hl[4] = 0xade682d1;
- hl[5] = 0x2b3e6c1f;
- hl[6] = 0xfb41bd6b;
- hl[7] = 0x137e2179;
-
- crypto_hashblocks_hl(hh, hl, m, n);
- n %= 128;
-
- for (let i = 0; i < n; i++) x[i] = m[b - n + i];
- x[n] = 128;
-
- n = 256 - 128 * (n < 112 ? 1 : 0);
- x[n - 9] = 0;
- ts64(x, n - 8, (b / 0x20000000) | 0, b << 3);
- crypto_hashblocks_hl(hh, hl, x, n);
-
- for (let i = 0; i < 8; i++) ts64(out, 8 * i, hh[i], hl[i]);
-
- return 0;
-}
-
-/**
- * Incremental version of crypto_hash.
- */
-export class HashState {
- private hh = new Int32Array(8);
- private hl = new Int32Array(8);
-
- private next = new Uint8Array(128);
- private p = 0;
- private total = 0;
-
- constructor() {
- this.hh[0] = 0x6a09e667;
- this.hh[1] = 0xbb67ae85;
- this.hh[2] = 0x3c6ef372;
- this.hh[3] = 0xa54ff53a;
- this.hh[4] = 0x510e527f;
- this.hh[5] = 0x9b05688c;
- this.hh[6] = 0x1f83d9ab;
- this.hh[7] = 0x5be0cd19;
-
- this.hl[0] = 0xf3bcc908;
- this.hl[1] = 0x84caa73b;
- this.hl[2] = 0xfe94f82b;
- this.hl[3] = 0x5f1d36f1;
- this.hl[4] = 0xade682d1;
- this.hl[5] = 0x2b3e6c1f;
- this.hl[6] = 0xfb41bd6b;
- this.hl[7] = 0x137e2179;
- }
-
- update(data: Uint8Array): HashState {
- this.total += data.length;
- let i = 0;
- while (i < data.length) {
- const r = 128 - this.p;
- if (r > data.length - i) {
- for (let j = 0; i + j < data.length; j++) {
- this.next[this.p + j] = data[i + j];
- }
- this.p += data.length - i;
- break;
- } else {
- for (let j = 0; this.p + j < 128; j++) {
- this.next[this.p + j] = data[i + j];
- }
- crypto_hashblocks_hl(this.hh, this.hl, this.next, 128);
- i += 128 - this.p;
- this.p = 0;
- }
- }
- return this;
- }
-
- finish(): Uint8Array {
- const out = new Uint8Array(64);
- let n = this.p;
- const x = new Uint8Array(256);
- const b = this.total;
- for (let i = 0; i < n; i++) x[i] = this.next[i];
- x[n] = 128;
-
- n = 256 - 128 * (n < 112 ? 1 : 0);
- x[n - 9] = 0;
- ts64(x, n - 8, (b / 0x20000000) | 0, b << 3);
- crypto_hashblocks_hl(this.hh, this.hl, x, n);
-
- for (let i = 0; i < 8; i++) ts64(out, 8 * i, this.hh[i], this.hl[i]);
- return out;
- }
-}
-
-function add(p: Float64Array[], q: Float64Array[]): void {
- const a = gf(),
- b = gf(),
- c = gf(),
- d = gf(),
- e = gf(),
- f = gf(),
- g = gf(),
- h = gf(),
- t = gf();
-
- Z(a, p[1], p[0]);
- Z(t, q[1], q[0]);
- M(a, a, t);
- A(b, p[0], p[1]);
- A(t, q[0], q[1]);
- M(b, b, t);
- M(c, p[3], q[3]);
- M(c, c, D2);
- M(d, p[2], q[2]);
- A(d, d, d);
- Z(e, b, a);
- Z(f, d, c);
- A(g, d, c);
- A(h, b, a);
-
- M(p[0], e, f);
- M(p[1], h, g);
- M(p[2], g, f);
- M(p[3], e, h);
-}
-
-function cswap(p: Float64Array[], q: Float64Array[], b: number): void {
- let i;
- for (i = 0; i < 4; i++) {
- sel25519(p[i], q[i], b);
- }
-}
-
-function pack(r: Uint8Array, p: Float64Array[]): void {
- const tx = gf(),
- ty = gf(),
- zi = gf();
- inv25519(zi, p[2]);
- M(tx, p[0], zi);
- M(ty, p[1], zi);
- pack25519(r, ty);
- r[31] ^= par25519(tx) << 7;
-}
-
-function scalarmult(p: Float64Array[], q: Float64Array[], s: Uint8Array): void {
- let b, i;
- set25519(p[0], gf0);
- set25519(p[1], gf1);
- set25519(p[2], gf1);
- set25519(p[3], gf0);
- for (i = 255; i >= 0; --i) {
- b = (s[(i / 8) | 0] >> (i & 7)) & 1;
- cswap(p, q, b);
- add(q, p);
- add(p, p);
- cswap(p, q, b);
- }
-}
-
-function scalarbase(p: Float64Array[], s: Uint8Array): void {
- const q = [gf(), gf(), gf(), gf()];
- set25519(q[0], X);
- set25519(q[1], Y);
- set25519(q[2], gf1);
- M(q[3], X, Y);
- scalarmult(p, q, s);
-}
-
-function crypto_sign_keypair(
- pk: Uint8Array,
- sk: Uint8Array,
- seeded: boolean,
-): number {
- const d = new Uint8Array(64);
- const p = [gf(), gf(), gf(), gf()];
-
- if (!seeded) randombytes(sk, 32);
- crypto_hash(d, sk, 32);
- d[0] &= 248;
- d[31] &= 127;
- d[31] |= 64;
-
- scalarbase(p, d);
- pack(pk, p);
-
- for (let i = 0; i < 32; i++) sk[i + 32] = pk[i];
- return 0;
-}
-
-const L = new Float64Array([
- 0xed,
- 0xd3,
- 0xf5,
- 0x5c,
- 0x1a,
- 0x63,
- 0x12,
- 0x58,
- 0xd6,
- 0x9c,
- 0xf7,
- 0xa2,
- 0xde,
- 0xf9,
- 0xde,
- 0x14,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0x10,
-]);
-
-function modL(r: Uint8Array, x: Float64Array): void {
- let carry, i, j, k;
- for (i = 63; i >= 32; --i) {
- carry = 0;
- for (j = i - 32, k = i - 12; j < k; ++j) {
- x[j] += carry - 16 * x[i] * L[j - (i - 32)];
- carry = (x[j] + 128) >> 8;
- x[j] -= carry * 256;
- }
- x[j] += carry;
- x[i] = 0;
- }
- carry = 0;
- for (j = 0; j < 32; j++) {
- x[j] += carry - (x[31] >> 4) * L[j];
- carry = x[j] >> 8;
- x[j] &= 255;
- }
- for (j = 0; j < 32; j++) x[j] -= carry * L[j];
- for (i = 0; i < 32; i++) {
- x[i + 1] += x[i] >> 8;
- r[i] = x[i] & 255;
- }
-}
-
-function reduce(r: Uint8Array): void {
- const x = new Float64Array(64);
- for (let i = 0; i < 64; i++) x[i] = r[i];
- for (let i = 0; i < 64; i++) r[i] = 0;
- modL(r, x);
-}
-
-// Note: difference from C - smlen returned, not passed as argument.
-function crypto_sign(
- sm: Uint8Array,
- m: Uint8Array,
- n: number,
- sk: Uint8Array,
-): number {
- const d = new Uint8Array(64),
- h = new Uint8Array(64),
- r = new Uint8Array(64);
- let i, j;
- const x = new Float64Array(64);
- const p = [gf(), gf(), gf(), gf()];
-
- crypto_hash(d, sk, 32);
- d[0] &= 248;
- d[31] &= 127;
- d[31] |= 64;
-
- const smlen = n + 64;
- for (i = 0; i < n; i++) sm[64 + i] = m[i];
- for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
-
- crypto_hash(r, sm.subarray(32), n + 32);
- reduce(r);
- scalarbase(p, r);
- pack(sm, p);
-
- for (i = 32; i < 64; i++) sm[i] = sk[i];
- crypto_hash(h, sm, n + 64);
- reduce(h);
-
- for (i = 0; i < 64; i++) x[i] = 0;
- for (i = 0; i < 32; i++) x[i] = r[i];
- for (i = 0; i < 32; i++) {
- for (j = 0; j < 32; j++) {
- x[i + j] += h[i] * d[j];
- }
- }
-
- modL(sm.subarray(32), x);
- return smlen;
-}
-
-function unpackneg(r: Float64Array[], p: Uint8Array): number {
- const t = gf();
- const chk = gf();
- const num = gf();
- const den = gf();
- const den2 = gf();
- const den4 = gf();
- const den6 = gf();
-
- set25519(r[2], gf1);
- unpack25519(r[1], p);
- S(num, r[1]);
- M(den, num, D);
- Z(num, num, r[2]);
- A(den, r[2], den);
-
- S(den2, den);
- S(den4, den2);
- M(den6, den4, den2);
- M(t, den6, num);
- M(t, t, den);
-
- pow2523(t, t);
- M(t, t, num);
- M(t, t, den);
- M(t, t, den);
- M(r[0], t, den);
-
- S(chk, r[0]);
- M(chk, chk, den);
- if (neq25519(chk, num)) M(r[0], r[0], I);
-
- S(chk, r[0]);
- M(chk, chk, den);
- if (neq25519(chk, num)) return -1;
-
- if (par25519(r[0]) === p[31] >> 7) Z(r[0], gf0, r[0]);
-
- M(r[3], r[0], r[1]);
- return 0;
-}
-
-function crypto_sign_open(
- m: Uint8Array,
- sm: Uint8Array,
- n: number,
- pk: Uint8Array,
-): number {
- let i, mlen;
- const t = new Uint8Array(32),
- h = new Uint8Array(64);
- const p = [gf(), gf(), gf(), gf()],
- q = [gf(), gf(), gf(), gf()];
-
- mlen = -1;
- if (n < 64) return -1;
-
- if (unpackneg(q, pk)) return -1;
-
- for (i = 0; i < n; i++) m[i] = sm[i];
- for (i = 0; i < 32; i++) m[i + 32] = pk[i];
- crypto_hash(h, m, n);
- reduce(h);
- scalarmult(p, q, h);
-
- scalarbase(q, sm.subarray(32));
- add(p, q);
- pack(t, p);
-
- n -= 64;
- if (crypto_verify_32(sm, 0, t, 0)) {
- for (i = 0; i < n; i++) m[i] = 0;
- return -1;
- }
-
- for (i = 0; i < n; i++) m[i] = sm[i + 64];
- mlen = n;
- return mlen;
-}
-
-const crypto_scalarmult_BYTES = 32,
- crypto_scalarmult_SCALARBYTES = 32,
- crypto_sign_BYTES = 64,
- crypto_sign_PUBLICKEYBYTES = 32,
- crypto_sign_SECRETKEYBYTES = 64,
- crypto_sign_SEEDBYTES = 32,
- crypto_hash_BYTES = 64;
-
-/* High-level API */
-
-function checkArrayTypes(...args: Uint8Array[]): void {
- for (let i = 0; i < args.length; i++) {
- if (!(args[i] instanceof Uint8Array))
- throw new TypeError("unexpected type, use Uint8Array");
- }
-}
-
-function cleanup(arr: Uint8Array): void {
- for (let i = 0; i < arr.length; i++) arr[i] = 0;
-}
-
-export function randomBytes(n: number): Uint8Array {
- const b = new Uint8Array(n);
- randombytes(b, n);
- return b;
-}
-
-export function scalarMult(n: Uint8Array, p: Uint8Array): Uint8Array {
- checkArrayTypes(n, p);
- if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error("bad n size");
- if (p.length !== crypto_scalarmult_BYTES) throw new Error("bad p size");
- const q = new Uint8Array(crypto_scalarmult_BYTES);
- crypto_scalarmult(q, n, p);
- return q;
-}
-
-export function scalarMult_base(n: Uint8Array): Uint8Array {
- checkArrayTypes(n);
- if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error("bad n size");
- const q = new Uint8Array(crypto_scalarmult_BYTES);
- crypto_scalarmult_base(q, n);
- return q;
-}
-
-export const scalarMult_scalarLength = crypto_scalarmult_SCALARBYTES;
-export const scalarMult_groupElementLength = crypto_scalarmult_BYTES;
-
-export function sign(msg: Uint8Array, secretKey: Uint8Array): Uint8Array {
- checkArrayTypes(msg, secretKey);
- if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
- throw new Error("bad secret key size");
- const signedMsg = new Uint8Array(crypto_sign_BYTES + msg.length);
- crypto_sign(signedMsg, msg, msg.length, secretKey);
- return signedMsg;
-}
-
-export function sign_open(
- signedMsg: Uint8Array,
- publicKey: Uint8Array,
-): Uint8Array | null {
- checkArrayTypes(signedMsg, publicKey);
- if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
- throw new Error("bad public key size");
- const tmp = new Uint8Array(signedMsg.length);
- const mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);
- if (mlen < 0) return null;
- const m = new Uint8Array(mlen);
- for (let i = 0; i < m.length; i++) m[i] = tmp[i];
- return m;
-}
-
-export function sign_detached(
- msg: Uint8Array,
- secretKey: Uint8Array,
-): Uint8Array {
- const signedMsg = sign(msg, secretKey);
- const sig = new Uint8Array(crypto_sign_BYTES);
- for (let i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
- return sig;
-}
-
-export function sign_detached_verify(
- msg: Uint8Array,
- sig: Uint8Array,
- publicKey: Uint8Array,
-): boolean {
- checkArrayTypes(msg, sig, publicKey);
- if (sig.length !== crypto_sign_BYTES) throw new Error("bad signature size");
- if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
- throw new Error("bad public key size");
- const sm = new Uint8Array(crypto_sign_BYTES + msg.length);
- const m = new Uint8Array(crypto_sign_BYTES + msg.length);
- let i;
- for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
- for (i = 0; i < msg.length; i++) sm[i + crypto_sign_BYTES] = msg[i];
- return crypto_sign_open(m, sm, sm.length, publicKey) >= 0;
-}
-
-export function sign_keyPair(): {
- publicKey: Uint8Array;
- secretKey: Uint8Array;
-} {
- const pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
- const sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
- crypto_sign_keypair(pk, sk, false);
- return { publicKey: pk, secretKey: sk };
-}
-
-export function x25519_edwards_keyPair_fromSecretKey(
- secretKey: Uint8Array,
-): Uint8Array {
- const p = [gf(), gf(), gf(), gf()];
- const pk = new Uint8Array(32);
-
- const d = new Uint8Array(64);
- if (secretKey.length != 32) {
- throw new Error("bad secret key size");
- }
- d.set(secretKey, 0);
- //crypto_hash(d, secretKey, 32);
-
- d[0] &= 248;
- d[31] &= 127;
- d[31] |= 64;
-
- scalarbase(p, d);
- pack(pk, p);
-
- return pk;
-}
-
-export function sign_keyPair_fromSecretKey(
- secretKey: Uint8Array,
-): {
- publicKey: Uint8Array;
- secretKey: Uint8Array;
-} {
- checkArrayTypes(secretKey);
- if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
- throw new Error("bad secret key size");
- const pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
- for (let i = 0; i < pk.length; i++) pk[i] = secretKey[32 + i];
- return { publicKey: pk, secretKey: new Uint8Array(secretKey) };
-}
-
-export function sign_keyPair_fromSeed(
- seed: Uint8Array,
-): {
- publicKey: Uint8Array;
- secretKey: Uint8Array;
-} {
- checkArrayTypes(seed);
- if (seed.length !== crypto_sign_SEEDBYTES) throw new Error("bad seed size");
- const pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
- const sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
- for (let i = 0; i < 32; i++) sk[i] = seed[i];
- crypto_sign_keypair(pk, sk, true);
- return { publicKey: pk, secretKey: sk };
-}
-
-export const sign_publicKeyLength = crypto_sign_PUBLICKEYBYTES;
-export const sign_secretKeyLength = crypto_sign_SECRETKEYBYTES;
-export const sign_seedLength = crypto_sign_SEEDBYTES;
-export const sign_signatureLength = crypto_sign_BYTES;
-
-export function hash(msg: Uint8Array): Uint8Array {
- checkArrayTypes(msg);
- const h = new Uint8Array(crypto_hash_BYTES);
- crypto_hash(h, msg, msg.length);
- return h;
-}
-
-export const hash_hashLength = crypto_hash_BYTES;
-
-export function verify(x: Uint8Array, y: Uint8Array): boolean {
- checkArrayTypes(x, y);
- // Zero length arguments are considered not equal.
- if (x.length === 0 || y.length === 0) return false;
- if (x.length !== y.length) return false;
- return vn(x, 0, y, 0, x.length) === 0 ? true : false;
-}
-
-export function setPRNG(fn: (x: Uint8Array, n: number) => void): void {
- randombytes = fn;
-}
-
-export function sign_ed25519_pk_to_curve25519(
- ed25519_pk: Uint8Array,
-): Uint8Array {
- const ge_a = [gf(), gf(), gf(), gf()];
- const x = gf();
- const one_minus_y = gf();
- const x25519_pk = new Uint8Array(32);
-
- if (unpackneg(ge_a, ed25519_pk)) {
- throw Error("invalid public key");
- }
-
- set25519(one_minus_y, gf1);
- Z(one_minus_y, one_minus_y, ge_a[1]);
-
- set25519(x, gf1);
- A(x, x, ge_a[1]);
-
- inv25519(one_minus_y, one_minus_y);
- M(x, x, one_minus_y);
- pack25519(x25519_pk, x);
-
- return x25519_pk;
-}
-
-(function () {
- // Initialize PRNG if environment provides CSPRNG.
- // If not, methods calling randombytes will throw.
- const cr =
- typeof self !== "undefined" ? self.crypto || (self as any).msCrypto : null;
- if (cr && cr.getRandomValues) {
- // Browsers.
- const QUOTA = 65536;
- setPRNG(function (x: Uint8Array, n: number) {
- let i;
- const v = new Uint8Array(n);
- for (i = 0; i < n; i += QUOTA) {
- cr.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
- }
- for (i = 0; i < n; i++) x[i] = v[i];
- cleanup(v);
- });
- } else if (typeof require !== "undefined") {
- // Node.js.
- // eslint-disable-next-line @typescript-eslint/no-var-requires
- const cr = require("crypto");
- if (cr && cr.randomBytes) {
- setPRNG(function (x: Uint8Array, n: number) {
- const v = cr.randomBytes(n);
- for (let i = 0; i < n; i++) x[i] = v[i];
- cleanup(v);
- });
- }
- }
-})();
diff --git a/src/crypto/primitives/sha256.ts b/src/crypto/primitives/sha256.ts
deleted file mode 100644
index 97723dbfc..000000000
--- a/src/crypto/primitives/sha256.ts
+++ /dev/null
@@ -1,426 +0,0 @@
-// SHA-256 for JavaScript.
-//
-// Written in 2014-2016 by Dmitry Chestnykh.
-// Public domain, no warranty.
-//
-// Functions (accept and return Uint8Arrays):
-//
-// sha256(message) -> hash
-// sha256.hmac(key, message) -> mac
-//
-// Classes:
-//
-// new sha256.Hash()
-export const digestLength = 32;
-export const blockSize = 64;
-
-// SHA-256 constants
-const K = new Uint32Array([
- 0x428a2f98,
- 0x71374491,
- 0xb5c0fbcf,
- 0xe9b5dba5,
- 0x3956c25b,
- 0x59f111f1,
- 0x923f82a4,
- 0xab1c5ed5,
- 0xd807aa98,
- 0x12835b01,
- 0x243185be,
- 0x550c7dc3,
- 0x72be5d74,
- 0x80deb1fe,
- 0x9bdc06a7,
- 0xc19bf174,
- 0xe49b69c1,
- 0xefbe4786,
- 0x0fc19dc6,
- 0x240ca1cc,
- 0x2de92c6f,
- 0x4a7484aa,
- 0x5cb0a9dc,
- 0x76f988da,
- 0x983e5152,
- 0xa831c66d,
- 0xb00327c8,
- 0xbf597fc7,
- 0xc6e00bf3,
- 0xd5a79147,
- 0x06ca6351,
- 0x14292967,
- 0x27b70a85,
- 0x2e1b2138,
- 0x4d2c6dfc,
- 0x53380d13,
- 0x650a7354,
- 0x766a0abb,
- 0x81c2c92e,
- 0x92722c85,
- 0xa2bfe8a1,
- 0xa81a664b,
- 0xc24b8b70,
- 0xc76c51a3,
- 0xd192e819,
- 0xd6990624,
- 0xf40e3585,
- 0x106aa070,
- 0x19a4c116,
- 0x1e376c08,
- 0x2748774c,
- 0x34b0bcb5,
- 0x391c0cb3,
- 0x4ed8aa4a,
- 0x5b9cca4f,
- 0x682e6ff3,
- 0x748f82ee,
- 0x78a5636f,
- 0x84c87814,
- 0x8cc70208,
- 0x90befffa,
- 0xa4506ceb,
- 0xbef9a3f7,
- 0xc67178f2,
-]);
-
-function hashBlocks(
- w: Int32Array,
- v: Int32Array,
- p: Uint8Array,
- pos: number,
- len: number,
-): number {
- let a: number,
- b: number,
- c: number,
- d: number,
- e: number,
- f: number,
- g: number,
- h: number,
- u: number,
- i: number,
- j: number,
- t1: number,
- t2: number;
- while (len >= 64) {
- a = v[0];
- b = v[1];
- c = v[2];
- d = v[3];
- e = v[4];
- f = v[5];
- g = v[6];
- h = v[7];
-
- for (i = 0; i < 16; i++) {
- j = pos + i * 4;
- w[i] =
- ((p[j] & 0xff) << 24) |
- ((p[j + 1] & 0xff) << 16) |
- ((p[j + 2] & 0xff) << 8) |
- (p[j + 3] & 0xff);
- }
-
- for (i = 16; i < 64; i++) {
- u = w[i - 2];
- t1 =
- ((u >>> 17) | (u << (32 - 17))) ^
- ((u >>> 19) | (u << (32 - 19))) ^
- (u >>> 10);
-
- u = w[i - 15];
- t2 =
- ((u >>> 7) | (u << (32 - 7))) ^
- ((u >>> 18) | (u << (32 - 18))) ^
- (u >>> 3);
-
- w[i] = ((t1 + w[i - 7]) | 0) + ((t2 + w[i - 16]) | 0);
- }
-
- for (i = 0; i < 64; i++) {
- t1 =
- ((((((e >>> 6) | (e << (32 - 6))) ^
- ((e >>> 11) | (e << (32 - 11))) ^
- ((e >>> 25) | (e << (32 - 25)))) +
- ((e & f) ^ (~e & g))) |
- 0) +
- ((h + ((K[i] + w[i]) | 0)) | 0)) |
- 0;
-
- t2 =
- ((((a >>> 2) | (a << (32 - 2))) ^
- ((a >>> 13) | (a << (32 - 13))) ^
- ((a >>> 22) | (a << (32 - 22)))) +
- ((a & b) ^ (a & c) ^ (b & c))) |
- 0;
-
- h = g;
- g = f;
- f = e;
- e = (d + t1) | 0;
- d = c;
- c = b;
- b = a;
- a = (t1 + t2) | 0;
- }
-
- v[0] += a;
- v[1] += b;
- v[2] += c;
- v[3] += d;
- v[4] += e;
- v[5] += f;
- v[6] += g;
- v[7] += h;
-
- pos += 64;
- len -= 64;
- }
- return pos;
-}
-
-// Hash implements SHA256 hash algorithm.
-export class HashSha256 {
- digestLength: number = digestLength;
- blockSize: number = blockSize;
-
- // Note: Int32Array is used instead of Uint32Array for performance reasons.
- private state: Int32Array = new Int32Array(8); // hash state
- private temp: Int32Array = new Int32Array(64); // temporary state
- private buffer: Uint8Array = new Uint8Array(128); // buffer for data to hash
- private bufferLength = 0; // number of bytes in buffer
- private bytesHashed = 0; // number of total bytes hashed
-
- finished = false; // indicates whether the hash was finalized
-
- constructor() {
- this.reset();
- }
-
- // Resets hash state making it possible
- // to re-use this instance to hash other data.
- reset(): this {
- this.state[0] = 0x6a09e667;
- this.state[1] = 0xbb67ae85;
- this.state[2] = 0x3c6ef372;
- this.state[3] = 0xa54ff53a;
- this.state[4] = 0x510e527f;
- this.state[5] = 0x9b05688c;
- this.state[6] = 0x1f83d9ab;
- this.state[7] = 0x5be0cd19;
- this.bufferLength = 0;
- this.bytesHashed = 0;
- this.finished = false;
- return this;
- }
-
- // Cleans internal buffers and re-initializes hash state.
- clean(): void {
- for (let i = 0; i < this.buffer.length; i++) {
- this.buffer[i] = 0;
- }
- for (let i = 0; i < this.temp.length; i++) {
- this.temp[i] = 0;
- }
- this.reset();
- }
-
- // Updates hash state with the given data.
- //
- // Optionally, length of the data can be specified to hash
- // fewer bytes than data.length.
- //
- // Throws error when trying to update already finalized hash:
- // instance must be reset to use it again.
- update(data: Uint8Array, dataLength: number = data.length): this {
- if (this.finished) {
- throw new Error("SHA256: can't update because hash was finished.");
- }
- let dataPos = 0;
- this.bytesHashed += dataLength;
- if (this.bufferLength > 0) {
- while (this.bufferLength < 64 && dataLength > 0) {
- this.buffer[this.bufferLength++] = data[dataPos++];
- dataLength--;
- }
- if (this.bufferLength === 64) {
- hashBlocks(this.temp, this.state, this.buffer, 0, 64);
- this.bufferLength = 0;
- }
- }
- if (dataLength >= 64) {
- dataPos = hashBlocks(this.temp, this.state, data, dataPos, dataLength);
- dataLength %= 64;
- }
- while (dataLength > 0) {
- this.buffer[this.bufferLength++] = data[dataPos++];
- dataLength--;
- }
- return this;
- }
-
- // Finalizes hash state and puts hash into out.
- //
- // If hash was already finalized, puts the same value.
- finish(out: Uint8Array): this {
- if (!this.finished) {
- const bytesHashed = this.bytesHashed;
- const left = this.bufferLength;
- const bitLenHi = (bytesHashed / 0x20000000) | 0;
- const bitLenLo = bytesHashed << 3;
- const padLength = bytesHashed % 64 < 56 ? 64 : 128;
-
- this.buffer[left] = 0x80;
- for (let i = left + 1; i < padLength - 8; i++) {
- this.buffer[i] = 0;
- }
- this.buffer[padLength - 8] = (bitLenHi >>> 24) & 0xff;
- this.buffer[padLength - 7] = (bitLenHi >>> 16) & 0xff;
- this.buffer[padLength - 6] = (bitLenHi >>> 8) & 0xff;
- this.buffer[padLength - 5] = (bitLenHi >>> 0) & 0xff;
- this.buffer[padLength - 4] = (bitLenLo >>> 24) & 0xff;
- this.buffer[padLength - 3] = (bitLenLo >>> 16) & 0xff;
- this.buffer[padLength - 2] = (bitLenLo >>> 8) & 0xff;
- this.buffer[padLength - 1] = (bitLenLo >>> 0) & 0xff;
-
- hashBlocks(this.temp, this.state, this.buffer, 0, padLength);
-
- this.finished = true;
- }
-
- for (let i = 0; i < 8; i++) {
- out[i * 4 + 0] = (this.state[i] >>> 24) & 0xff;
- out[i * 4 + 1] = (this.state[i] >>> 16) & 0xff;
- out[i * 4 + 2] = (this.state[i] >>> 8) & 0xff;
- out[i * 4 + 3] = (this.state[i] >>> 0) & 0xff;
- }
-
- return this;
- }
-
- // Returns the final hash digest.
- digest(): Uint8Array {
- const out = new Uint8Array(this.digestLength);
- this.finish(out);
- return out;
- }
-
- // Internal function for use in HMAC for optimization.
- _saveState(out: Uint32Array): void {
- for (let i = 0; i < this.state.length; i++) {
- out[i] = this.state[i];
- }
- }
-
- // Internal function for use in HMAC for optimization.
- _restoreState(from: Uint32Array, bytesHashed: number): void {
- for (let i = 0; i < this.state.length; i++) {
- this.state[i] = from[i];
- }
- this.bytesHashed = bytesHashed;
- this.finished = false;
- this.bufferLength = 0;
- }
-}
-
-// HMAC implements HMAC-SHA256 message authentication algorithm.
-export class HMAC {
- private inner: HashSha256 = new HashSha256();
- private outer: HashSha256 = new HashSha256();
-
- blockSize: number = this.inner.blockSize;
- digestLength: number = this.inner.digestLength;
-
- // Copies of hash states after keying.
- // Need for quick reset without hashing they key again.
- private istate: Uint32Array;
- private ostate: Uint32Array;
-
- constructor(key: Uint8Array) {
- const pad = new Uint8Array(this.blockSize);
- if (key.length > this.blockSize) {
- new HashSha256().update(key).finish(pad).clean();
- } else {
- for (let i = 0; i < key.length; i++) {
- pad[i] = key[i];
- }
- }
- for (let i = 0; i < pad.length; i++) {
- pad[i] ^= 0x36;
- }
- this.inner.update(pad);
-
- for (let i = 0; i < pad.length; i++) {
- pad[i] ^= 0x36 ^ 0x5c;
- }
- this.outer.update(pad);
-
- this.istate = new Uint32Array(8);
- this.ostate = new Uint32Array(8);
-
- this.inner._saveState(this.istate);
- this.outer._saveState(this.ostate);
-
- for (let i = 0; i < pad.length; i++) {
- pad[i] = 0;
- }
- }
-
- // Returns HMAC state to the state initialized with key
- // to make it possible to run HMAC over the other data with the same
- // key without creating a new instance.
- reset(): this {
- this.inner._restoreState(this.istate, this.inner.blockSize);
- this.outer._restoreState(this.ostate, this.outer.blockSize);
- return this;
- }
-
- // Cleans HMAC state.
- clean(): void {
- for (let i = 0; i < this.istate.length; i++) {
- this.ostate[i] = this.istate[i] = 0;
- }
- this.inner.clean();
- this.outer.clean();
- }
-
- // Updates state with provided data.
- update(data: Uint8Array): this {
- this.inner.update(data);
- return this;
- }
-
- // Finalizes HMAC and puts the result in out.
- finish(out: Uint8Array): this {
- if (this.outer.finished) {
- this.outer.finish(out);
- } else {
- this.inner.finish(out);
- this.outer.update(out, this.digestLength).finish(out);
- }
- return this;
- }
-
- // Returns message authentication code.
- digest(): Uint8Array {
- const out = new Uint8Array(this.digestLength);
- this.finish(out);
- return out;
- }
-}
-
-// Returns SHA256 hash of data.
-export function sha256(data: Uint8Array): Uint8Array {
- const h = new HashSha256().update(data);
- const digest = h.digest();
- h.clean();
- return digest;
-}
-
-// Returns HMAC-SHA256 of data under the key.
-export function hmacSha256(key: Uint8Array, data: Uint8Array): Uint8Array {
- const h = new HMAC(key).update(data);
- const digest = h.digest();
- h.clean();
- return digest;
-}
diff --git a/src/crypto/talerCrypto-test.ts b/src/crypto/talerCrypto-test.ts
deleted file mode 100644
index 1cd9da3e2..000000000
--- a/src/crypto/talerCrypto-test.ts
+++ /dev/null
@@ -1,197 +0,0 @@
-/*
- 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/>
- */
-
-/**
- * Imports
- */
-import test from "ava";
-import {
- encodeCrock,
- decodeCrock,
- ecdheGetPublic,
- eddsaGetPublic,
- keyExchangeEddsaEcdhe,
- keyExchangeEcdheEddsa,
- rsaBlind,
- rsaUnblind,
- rsaVerify,
-} from "./talerCrypto";
-import { sha512, kdf } from "./primitives/kdf";
-import * as nacl from "./primitives/nacl-fast";
-
-test("encoding", (t) => {
- const utf8decoder = new TextDecoder("utf-8");
- const utf8encoder = new TextEncoder();
- const s = "Hello, World";
- const encStr = encodeCrock(utf8encoder.encode(s));
- const outBuf = decodeCrock(encStr);
- const sOut = utf8decoder.decode(outBuf);
- t.deepEqual(s, sOut);
-});
-
-test("taler-exchange-tvg hash code", (t) => {
- const input = "91JPRV3F5GG4EKJN41A62V35E8";
- const output =
- "CW96WR74JS8T53EC8GKSGD49QKH4ZNFTZXDAWMMV5GJ1E4BM6B8GPN5NVHDJ8ZVXNCW7Q4WBYCV61HCA3PZC2YJD850DT29RHHN7ESR";
-
- const myOutput = encodeCrock(sha512(decodeCrock(input)));
-
- t.deepEqual(myOutput, output);
-});
-
-test("taler-exchange-tvg ecdhe key", (t) => {
- const priv1 = "X4T4N0M8PVQXQEBW2BA7049KFSM7J437NSDFC6GDNM3N5J9367A0";
- const pub1 = "M997P494MS6A95G1P0QYWW2VNPSHSX5Q6JBY5B9YMNYWP0B50X3G";
- const priv2 = "14A0MMQ64DCV8HE0CS3WBC9DHFJAHXRGV7NEARFJPC5R5E1697E0";
- const skm =
- "NXRY2YCY7H9B6KM928ZD55WG964G59YR0CPX041DYXKBZZ85SAWNPQ8B30QRM5FMHYCXJAN0EAADJYWEF1X3PAC2AJN28626TR5A6AR";
-
- const myPub1 = nacl.scalarMult_base(decodeCrock(priv1));
- t.deepEqual(encodeCrock(myPub1), pub1);
-
- const mySkm = nacl.hash(
- nacl.scalarMult(decodeCrock(priv2), decodeCrock(pub1)),
- );
- t.deepEqual(encodeCrock(mySkm), skm);
-});
-
-test("taler-exchange-tvg eddsa key", (t) => {
- const priv = "9TM70AKDTS57AWY9JK2J4TMBTMW6K62WHHGZWYDG0VM5ABPZKD40";
- const pub = "8GSJZ649T2PXMKZC01Y4ANNBE7MF14QVK9SQEC4E46ZHKCVG8AS0";
-
- const pair = nacl.sign_keyPair_fromSeed(decodeCrock(priv));
- t.deepEqual(encodeCrock(pair.publicKey), pub);
-});
-
-test("taler-exchange-tvg kdf", (t) => {
- const salt = "94KPT83PCNS7J83KC5P78Y8";
- const ikm = "94KPT83MD1JJ0WV5CDS6AX10D5Q70XBM41NPAY90DNGQ8SBJD5GPR";
- const ctx =
- "94KPT83141HPYVKMCNW78833D1TPWTSC41GPRWVF41NPWVVQDRG62WS04XMPWSKF4WG6JVH0EHM6A82J8S1G";
- const outLen = 64;
- const out =
- "GTMR4QT05Z9WF5HKVG0WK9RPXGHSMHJNW377G9GJXCA8B0FEKPF4D27RJMSJZYWSQNTBJ5EYVV7ZW18B48Z0JVJJ80RHB706Y96Q358";
-
- const myOut = kdf(
- outLen,
- decodeCrock(ikm),
- decodeCrock(salt),
- decodeCrock(ctx),
- );
-
- t.deepEqual(encodeCrock(myOut), out);
-});
-
-test("taler-exchange-tvg eddsa_ecdh", (t) => {
- const priv_ecdhe = "4AFZWMSGTVCHZPQ0R81NWXDCK4N58G7SDBBE5KXE080Y50370JJG";
- const pub_ecdhe = "FXFN5GPAFTKVPWJDPVXQ87167S8T82T5ZV8CDYC0NH2AE14X0M30";
- const priv_eddsa = "1KG54M8T3X8BSFSZXCR3SQBSR7Y9P53NX61M864S7TEVMJ2XVPF0";
- const pub_eddsa = "7BXWKG6N224C57RTDV8XEAHR108HG78NMA995BE8QAT5GC1S7E80";
- const key_material =
- "PKZ42Z56SVK2796HG1QYBRJ6ZQM2T9QGA3JA4AAZ8G7CWK9FPX175Q9JE5P0ZAX3HWWPHAQV4DPCK10R9X3SAXHRV0WF06BHEC2ZTKR";
-
- const myEcdhePub = ecdheGetPublic(decodeCrock(priv_ecdhe));
- t.deepEqual(encodeCrock(myEcdhePub), pub_ecdhe);
-
- const myEddsaPub = eddsaGetPublic(decodeCrock(priv_eddsa));
- t.deepEqual(encodeCrock(myEddsaPub), pub_eddsa);
-
- const myKm1 = keyExchangeEddsaEcdhe(
- decodeCrock(priv_eddsa),
- decodeCrock(pub_ecdhe),
- );
- t.deepEqual(encodeCrock(myKm1), key_material);
-
- const myKm2 = keyExchangeEcdheEddsa(
- decodeCrock(priv_ecdhe),
- decodeCrock(pub_eddsa),
- );
- t.deepEqual(encodeCrock(myKm2), key_material);
-});
-
-test("taler-exchange-tvg blind signing", (t) => {
- const messageHash =
- "TT1R28D79EJEJ9PC35AQS35CCG85DSXSZ508MV2HS2FN4ME6AHESZX5WP485R8A75KG53FN6F1YNW95008663TKAPWB81420VG17BY8";
- const rsaPublicKey =
- "040000Y62RSDDKZXTE7GDVA302ZZR0DY224RSDT6WDWR1XGT8E3YG80XV6TMT3ZCNP8XC84W0N6MSZ0EF8S3YB1JJ2AXY9JQZW3MCA0CG38ER4YE2RY4Q2666DEZSNKT29V6CKZVCDHXSAKY8W6RPEKEQ5YSBYQK23MRK3CQTNNJXQFDKEMRHEC5Y6RDHAC5RJCV8JJ8BF18VPKZ2Q7BB14YN1HJ22H8EZGW0RDGG9YPEWA9183BHEQ651PP81J514TJ9K8DH23AJ50SZFNS429HQ390VRP5E4MQ7RK7ZJXXTSZAQSRTC0QF28P23PD37C17QFQB0BBC54MB8MDH7RW104STG6VN0J22P39JP4EXPVGK5D9AX5W869MDQ6SRD42ZYK5H20227Q8CCWSQ6C3132WP0F0H04002";
- const bks = "7QD31RPJH0W306RJWBRG646Z2FTA1F89BKSXPDAG7YM0N5Z0B610";
- const bm =
- "GA8PC6YH9VF5MW6P2DKTV0W0ZTQ24DZ9EAN5QH3SQXRH7SCZHFMM21ZY05F0BS7MFW8TSEP4SEB280BYP5ACHNQWGE10PCXDDMK7ECXJDPHJ224JBCV4KYNWG6NBR3SC9HK8FXVFX55GFBJFNQHNZGEB8DB0KN9MSVYFDXN45KPMSNY03FVX0JZ0R3YG9XQ8XVGB5SYZCF0QSHWH61MT0Q10CZD2V114BT64D3GD86EJ5S9WBMYG51SDN5CSKEJ734YAJ4HCEWW0RDN8GXA9ZMA18SKVW8T3TTBCPJRF2Y77JGQ08GF35SYGA2HWFV1HGVS8RCTER6GB9SZHRG4T7919H9C1KFAP50G2KSV6X42D6KNJANNSGKQH649TJ00YJQXPHPNFBSS198RY2C243D4B4W";
- const bs =
- "5VW0MS5PRBA3W8TPATSTDA2YRFQM1Z7F2DWKQ8ATMZYYY768Q3STZ3HGNVYQ6JB5NKP80G5HGE58616FPA70SX9PTW7EN8EJ23E26FASBWZBP8E2RWQQ5E0F72B2PWRP5ZCA2J3AB3F6P86XK4PZYT64RF94MDGHY0GSDSSBH5YSFB3VM0KVXA52H2Y2G9S85AVCSD3BTMHQRF5BJJ8JE00T4GK70PSTVCGMRKRNA7DGW7GD2F35W55AXF7R2YJC8PAGNSJYWKC3PC75A5N8H69K299AK5PM3CDDHNS4BMRNGF7K49CR4ZBFRXDAWMB3X6T05Q4NKSG0F1KP5JA0XBMF2YJK7KEPRD1EWCHJE44T9YXBTK4W9CV77X7Z9P407ZC6YB3M2ARANZXHJKSM3XC33M";
- const sig =
- "PFT6WQJGCM9DE6264DJS6RMG4XDMCDBJKZGSXAF3BEXWZ979Q13NETKK05S1YV91CX3Y034FSS86SSHZTTE8097RRESQP52EKFGTWJXKHZJEQJ49YHMBNQDHW4CFBJECNJSV2PMHWVGXV7HB84R6P0S3ES559HWQX01Q9MYDEGRNHKW87QR2BNSG951D5NQGAKEJ2SSJBE18S6WYAC24FAP8TT8ANECH5371J0DJY0YR0VWAFWVJDV8XQSFXWMJ80N3A80SPSHPYJY3WZZXW63WQ46WHYY56ZSNE5G1RZ5CR0XYV2ECKPM8R0FS58EV16WTRAM1ABBFVNAT3CAEFAZCWP3XHPVBQY5NZVTD5QS2Q8SKJQ2XB30E11CWDN9KTV5CBK4DN72EVG73F3W3BATAKHG";
-
- const myBm = rsaBlind(
- decodeCrock(messageHash),
- decodeCrock(bks),
- decodeCrock(rsaPublicKey),
- );
- t.deepEqual(encodeCrock(myBm), bm);
-
- const mySig = rsaUnblind(
- decodeCrock(bs),
- decodeCrock(rsaPublicKey),
- decodeCrock(bks),
- );
- t.deepEqual(encodeCrock(mySig), sig);
-
- const v = rsaVerify(
- decodeCrock(messageHash),
- decodeCrock(sig),
- decodeCrock(rsaPublicKey),
- );
- t.true(v);
-});
-
-test("incremental hashing #1", (t) => {
- const n = 1024;
- const d = nacl.randomBytes(n);
-
- const h1 = nacl.hash(d);
- const h2 = new nacl.HashState().update(d).finish();
-
- const s = new nacl.HashState();
- for (let i = 0; i < n; i++) {
- const b = new Uint8Array(1);
- b[0] = d[i];
- s.update(b);
- }
-
- const h3 = s.finish();
-
- t.deepEqual(encodeCrock(h1), encodeCrock(h2));
- t.deepEqual(encodeCrock(h1), encodeCrock(h3));
-});
-
-test("incremental hashing #2", (t) => {
- const n = 10;
- const d = nacl.randomBytes(n);
-
- const h1 = nacl.hash(d);
- const h2 = new nacl.HashState().update(d).finish();
- const s = new nacl.HashState();
- for (let i = 0; i < n; i++) {
- const b = new Uint8Array(1);
- b[0] = d[i];
- s.update(b);
- }
-
- const h3 = s.finish();
-
- t.deepEqual(encodeCrock(h1), encodeCrock(h3));
- t.deepEqual(encodeCrock(h1), encodeCrock(h2));
-});
diff --git a/src/crypto/talerCrypto.ts b/src/crypto/talerCrypto.ts
deleted file mode 100644
index 457009a04..000000000
--- a/src/crypto/talerCrypto.ts
+++ /dev/null
@@ -1,376 +0,0 @@
-/*
- 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/>
- */
-
-/**
- * Native implementation of GNU Taler crypto.
- */
-
-import * as nacl from "./primitives/nacl-fast";
-import bigint from "big-integer";
-import { kdf } from "./primitives/kdf";
-
-export function getRandomBytes(n: number): Uint8Array {
- return nacl.randomBytes(n);
-}
-
-const encTable = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
-
-class EncodingError extends Error {
- constructor() {
- super("Encoding error");
- Object.setPrototypeOf(this, EncodingError.prototype);
- }
-}
-
-function getValue(chr: string): number {
- let a = chr;
- switch (chr) {
- case "O":
- case "o":
- a = "0;";
- break;
- case "i":
- case "I":
- case "l":
- case "L":
- a = "1";
- break;
- case "u":
- case "U":
- a = "V";
- }
-
- if (a >= "0" && a <= "9") {
- return a.charCodeAt(0) - "0".charCodeAt(0);
- }
-
- if (a >= "a" && a <= "z") a = a.toUpperCase();
- let dec = 0;
- if (a >= "A" && a <= "Z") {
- if ("I" < a) dec++;
- if ("L" < a) dec++;
- if ("O" < a) dec++;
- if ("U" < a) dec++;
- return a.charCodeAt(0) - "A".charCodeAt(0) + 10 - dec;
- }
- throw new EncodingError();
-}
-
-export function encodeCrock(data: ArrayBuffer): string {
- const dataBytes = new Uint8Array(data);
- let sb = "";
- const size = data.byteLength;
- let bitBuf = 0;
- let numBits = 0;
- let pos = 0;
- while (pos < size || numBits > 0) {
- if (pos < size && numBits < 5) {
- const d = dataBytes[pos++];
- bitBuf = (bitBuf << 8) | d;
- numBits += 8;
- }
- if (numBits < 5) {
- // zero-padding
- bitBuf = bitBuf << (5 - numBits);
- numBits = 5;
- }
- const v = (bitBuf >>> (numBits - 5)) & 31;
- sb += encTable[v];
- numBits -= 5;
- }
- return sb;
-}
-
-export function decodeCrock(encoded: string): Uint8Array {
- const size = encoded.length;
- let bitpos = 0;
- let bitbuf = 0;
- let readPosition = 0;
- const outLen = Math.floor((size * 5) / 8);
- const out = new Uint8Array(outLen);
- let outPos = 0;
-
- while (readPosition < size || bitpos > 0) {
- if (readPosition < size) {
- const v = getValue(encoded[readPosition++]);
- bitbuf = (bitbuf << 5) | v;
- bitpos += 5;
- }
- while (bitpos >= 8) {
- const d = (bitbuf >>> (bitpos - 8)) & 0xff;
- out[outPos++] = d;
- bitpos -= 8;
- }
- if (readPosition == size && bitpos > 0) {
- bitbuf = (bitbuf << (8 - bitpos)) & 0xff;
- bitpos = bitbuf == 0 ? 0 : 8;
- }
- }
- return out;
-}
-
-export function eddsaGetPublic(eddsaPriv: Uint8Array): Uint8Array {
- const pair = nacl.sign_keyPair_fromSeed(eddsaPriv);
- return pair.publicKey;
-}
-
-export function ecdheGetPublic(ecdhePriv: Uint8Array): Uint8Array {
- return nacl.scalarMult_base(ecdhePriv);
-}
-
-export function keyExchangeEddsaEcdhe(
- eddsaPriv: Uint8Array,
- ecdhePub: Uint8Array,
-): Uint8Array {
- const ph = nacl.hash(eddsaPriv);
- const a = new Uint8Array(32);
- for (let i = 0; i < 32; i++) {
- a[i] = ph[i];
- }
- const x = nacl.scalarMult(a, ecdhePub);
- return nacl.hash(x);
-}
-
-export function keyExchangeEcdheEddsa(
- ecdhePriv: Uint8Array,
- eddsaPub: Uint8Array,
-): Uint8Array {
- const curve25519Pub = nacl.sign_ed25519_pk_to_curve25519(eddsaPub);
- const x = nacl.scalarMult(ecdhePriv, curve25519Pub);
- return nacl.hash(x);
-}
-
-interface RsaPub {
- N: bigint.BigInteger;
- e: bigint.BigInteger;
-}
-
-interface RsaBlindingKey {
- r: bigint.BigInteger;
-}
-
-/**
- * KDF modulo a big integer.
- */
-function kdfMod(
- n: bigint.BigInteger,
- ikm: Uint8Array,
- salt: Uint8Array,
- info: Uint8Array,
-): bigint.BigInteger {
- const nbits = n.bitLength().toJSNumber();
- const buflen = Math.floor((nbits - 1) / 8 + 1);
- const mask = (1 << (8 - (buflen * 8 - nbits))) - 1;
- let counter = 0;
- while (true) {
- const ctx = new Uint8Array(info.byteLength + 2);
- ctx.set(info, 0);
- ctx[ctx.length - 2] = (counter >>> 8) & 0xff;
- ctx[ctx.length - 1] = counter & 0xff;
- const buf = kdf(buflen, ikm, salt, ctx);
- const arr = Array.from(buf);
- arr[0] = arr[0] & mask;
- const r = bigint.fromArray(arr, 256, false);
- if (r.lt(n)) {
- return r;
- }
- counter++;
- }
-}
-
-export function stringToBytes(s: string): Uint8Array {
- const te = new TextEncoder();
- return te.encode(s);
-}
-
-function loadBigInt(arr: Uint8Array): bigint.BigInteger {
- return bigint.fromArray(Array.from(arr), 256, false);
-}
-
-function rsaBlindingKeyDerive(
- rsaPub: RsaPub,
- bks: Uint8Array,
-): bigint.BigInteger {
- const salt = stringToBytes("Blinding KDF extrator HMAC key");
- const info = stringToBytes("Blinding KDF");
- return kdfMod(rsaPub.N, bks, salt, info);
-}
-
-/*
- * Test for malicious RSA key.
- *
- * Assuming n is an RSA modulous and r is generated using a call to
- * GNUNET_CRYPTO_kdf_mod_mpi, if gcd(r,n) != 1 then n must be a
- * malicious RSA key designed to deanomize the user.
- *
- * @param r KDF result
- * @param n RSA modulus of the public key
- */
-function rsaGcdValidate(r: bigint.BigInteger, n: bigint.BigInteger): void {
- const t = bigint.gcd(r, n);
- if (!t.equals(bigint.one)) {
- throw Error("malicious RSA public key");
- }
-}
-
-function rsaFullDomainHash(hm: Uint8Array, rsaPub: RsaPub): bigint.BigInteger {
- const info = stringToBytes("RSA-FDA FTpsW!");
- const salt = rsaPubEncode(rsaPub);
- const r = kdfMod(rsaPub.N, hm, salt, info);
- rsaGcdValidate(r, rsaPub.N);
- return r;
-}
-
-function rsaPubDecode(rsaPub: Uint8Array): RsaPub {
- const modulusLength = (rsaPub[0] << 8) | rsaPub[1];
- const exponentLength = (rsaPub[2] << 8) | rsaPub[3];
- if (4 + exponentLength + modulusLength != rsaPub.length) {
- throw Error("invalid RSA public key (format wrong)");
- }
- const modulus = rsaPub.slice(4, 4 + modulusLength);
- const exponent = rsaPub.slice(
- 4 + modulusLength,
- 4 + modulusLength + exponentLength,
- );
- const res = {
- N: loadBigInt(modulus),
- e: loadBigInt(exponent),
- };
- return res;
-}
-
-function rsaPubEncode(rsaPub: RsaPub): Uint8Array {
- const mb = rsaPub.N.toArray(256).value;
- const eb = rsaPub.e.toArray(256).value;
- const out = new Uint8Array(4 + mb.length + eb.length);
- out[0] = (mb.length >>> 8) & 0xff;
- out[1] = mb.length & 0xff;
- out[2] = (eb.length >>> 8) & 0xff;
- out[3] = eb.length & 0xff;
- out.set(mb, 4);
- out.set(eb, 4 + mb.length);
- return out;
-}
-
-export function rsaBlind(
- hm: Uint8Array,
- bks: Uint8Array,
- rsaPubEnc: Uint8Array,
-): Uint8Array {
- const rsaPub = rsaPubDecode(rsaPubEnc);
- const data = rsaFullDomainHash(hm, rsaPub);
- const r = rsaBlindingKeyDerive(rsaPub, bks);
- const r_e = r.modPow(rsaPub.e, rsaPub.N);
- const bm = r_e.multiply(data).mod(rsaPub.N);
- return new Uint8Array(bm.toArray(256).value);
-}
-
-export function rsaUnblind(
- sig: Uint8Array,
- rsaPubEnc: Uint8Array,
- bks: Uint8Array,
-): Uint8Array {
- const rsaPub = rsaPubDecode(rsaPubEnc);
- const blinded_s = loadBigInt(sig);
- const r = rsaBlindingKeyDerive(rsaPub, bks);
- const r_inv = r.modInv(rsaPub.N);
- const s = blinded_s.multiply(r_inv).mod(rsaPub.N);
- return new Uint8Array(s.toArray(256).value);
-}
-
-export function rsaVerify(
- hm: Uint8Array,
- rsaSig: Uint8Array,
- rsaPubEnc: Uint8Array,
-): boolean {
- const rsaPub = rsaPubDecode(rsaPubEnc);
- const d = rsaFullDomainHash(hm, rsaPub);
- const sig = loadBigInt(rsaSig);
- const sig_e = sig.modPow(rsaPub.e, rsaPub.N);
- return sig_e.equals(d);
-}
-
-export interface EddsaKeyPair {
- eddsaPub: Uint8Array;
- eddsaPriv: Uint8Array;
-}
-
-export interface EcdheKeyPair {
- ecdhePub: Uint8Array;
- ecdhePriv: Uint8Array;
-}
-
-export function createEddsaKeyPair(): EddsaKeyPair {
- const eddsaPriv = nacl.randomBytes(32);
- const eddsaPub = eddsaGetPublic(eddsaPriv);
- return { eddsaPriv, eddsaPub };
-}
-
-export function createEcdheKeyPair(): EcdheKeyPair {
- const ecdhePriv = nacl.randomBytes(32);
- const ecdhePub = ecdheGetPublic(ecdhePriv);
- return { ecdhePriv, ecdhePub };
-}
-
-export function createBlindingKeySecret(): Uint8Array {
- return nacl.randomBytes(32);
-}
-
-export function hash(d: Uint8Array): Uint8Array {
- return nacl.hash(d);
-}
-
-export function eddsaSign(msg: Uint8Array, eddsaPriv: Uint8Array): Uint8Array {
- const pair = nacl.sign_keyPair_fromSeed(eddsaPriv);
- return nacl.sign_detached(msg, pair.secretKey);
-}
-
-export function eddsaVerify(
- msg: Uint8Array,
- sig: Uint8Array,
- eddsaPub: Uint8Array,
-): boolean {
- return nacl.sign_detached_verify(msg, sig, eddsaPub);
-}
-
-export function createHashContext(): nacl.HashState {
- return new nacl.HashState();
-}
-
-export interface FreshCoin {
- coinPub: Uint8Array;
- coinPriv: Uint8Array;
- bks: Uint8Array;
-}
-
-export function setupRefreshPlanchet(
- secretSeed: Uint8Array,
- coinNumber: number,
-): FreshCoin {
- const info = stringToBytes("taler-coin-derivation");
- const saltArrBuf = new ArrayBuffer(4);
- const salt = new Uint8Array(saltArrBuf);
- const saltDataView = new DataView(saltArrBuf);
- saltDataView.setUint32(0, coinNumber);
- const out = kdf(64, secretSeed, salt, info);
- const coinPriv = out.slice(0, 32);
- const bks = out.slice(32, 64);
- return {
- bks,
- coinPriv,
- coinPub: eddsaGetPublic(coinPriv),
- };
-}
diff --git a/src/crypto/workers/browserWorkerEntry.ts b/src/crypto/workers/browserWorkerEntry.ts
deleted file mode 100644
index 87cb0b28b..000000000
--- a/src/crypto/workers/browserWorkerEntry.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
-*/
-
-/**
- * Web worker for crypto operations.
- */
-
-/**
- * Imports.
- */
-
-import { CryptoImplementation } from "./cryptoImplementation";
-
-const worker: Worker = (self as any) as Worker;
-
-async function handleRequest(
- operation: string,
- id: number,
- args: string[],
-): Promise<void> {
- const impl = new CryptoImplementation();
-
- if (!(operation in impl)) {
- console.error(`crypto operation '${operation}' not found`);
- return;
- }
-
- try {
- const result = (impl as any)[operation](...args);
- worker.postMessage({ result, id });
- } catch (e) {
- console.log("error during operation", e);
- return;
- }
-}
-
-worker.onmessage = (msg: MessageEvent) => {
- const args = msg.data.args;
- if (!Array.isArray(args)) {
- console.error("args must be array");
- return;
- }
- const id = msg.data.id;
- if (typeof id !== "number") {
- console.error("RPC id must be number");
- return;
- }
- const operation = msg.data.operation;
- if (typeof operation !== "string") {
- console.error("RPC operation must be string");
- return;
- }
-
- if (CryptoImplementation.enableTracing) {
- console.log("onmessage with", operation);
- }
-
- handleRequest(operation, id, args).catch((e) => {
- console.error("error in browsere worker", e);
- });
-};
diff --git a/src/crypto/workers/cryptoApi.ts b/src/crypto/workers/cryptoApi.ts
deleted file mode 100644
index 5e922ec02..000000000
--- a/src/crypto/workers/cryptoApi.ts
+++ /dev/null
@@ -1,467 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * API to access the Taler crypto worker thread.
- * @author Florian Dold
- */
-
-/**
- * Imports.
- */
-import { AmountJson } from "../../util/amounts";
-
-import {
- CoinRecord,
- DenominationRecord,
- RefreshSessionRecord,
- TipPlanchet,
- WireFee,
- DenominationSelectionInfo,
-} from "../../types/dbTypes";
-
-import { CryptoWorker } from "./cryptoWorker";
-
-import { RecoupRequest, CoinDepositPermission } from "../../types/talerTypes";
-
-import {
- BenchmarkResult,
- PlanchetCreationResult,
- PlanchetCreationRequest,
- DepositInfo,
-} from "../../types/walletTypes";
-
-import * as timer from "../../util/timer";
-import { Logger } from "../../util/logging";
-
-const logger = new Logger("cryptoApi.ts");
-
-/**
- * State of a crypto worker.
- */
-interface WorkerState {
- /**
- * The actual worker thread.
- */
- w: CryptoWorker | null;
-
- /**
- * Work we're currently executing or null if not busy.
- */
- currentWorkItem: WorkItem | null;
-
- /**
- * Timer to terminate the worker if it's not busy enough.
- */
- terminationTimerHandle: timer.TimerHandle | null;
-}
-
-interface WorkItem {
- operation: string;
- args: any[];
- resolve: any;
- reject: any;
-
- /**
- * Serial id to identify a matching response.
- */
- rpcId: number;
-
- /**
- * Time when the work was submitted to a (non-busy) worker thread.
- */
- startTime: number;
-}
-
-/**
- * Number of different priorities. Each priority p
- * must be 0 <= p < NUM_PRIO.
- */
-const NUM_PRIO = 5;
-
-export interface CryptoWorkerFactory {
- /**
- * Start a new worker.
- */
- startWorker(): CryptoWorker;
-
- /**
- * Query the number of workers that should be
- * run at the same time.
- */
- getConcurrency(): number;
-}
-
-export class BrowserCryptoWorkerFactory implements CryptoWorkerFactory {
- startWorker(): CryptoWorker {
- const workerCtor = Worker;
- const workerPath = "/browserWorkerEntry.js";
- return new workerCtor(workerPath) as CryptoWorker;
- }
-
- getConcurrency(): number {
- let concurrency = 2;
- try {
- // only works in the browser
- // tslint:disable-next-line:no-string-literal
- concurrency = (navigator as any)["hardwareConcurrency"];
- concurrency = Math.max(1, Math.ceil(concurrency / 2));
- } catch (e) {
- concurrency = 2;
- }
- return concurrency;
- }
-}
-
-/**
- * Crypto API that interfaces manages a background crypto thread
- * for the execution of expensive operations.
- */
-export class CryptoApi {
- private nextRpcId = 1;
- private workers: WorkerState[];
- private workQueues: WorkItem[][];
-
- private workerFactory: CryptoWorkerFactory;
-
- /**
- * Number of busy workers.
- */
- private numBusy = 0;
-
- /**
- * Did we stop accepting new requests?
- */
- private stopped = false;
-
- /**
- * Terminate all worker threads.
- */
- terminateWorkers(): void {
- for (const worker of this.workers) {
- if (worker.w) {
- logger.trace("terminating worker");
- worker.w.terminate();
- if (worker.terminationTimerHandle) {
- worker.terminationTimerHandle.clear();
- worker.terminationTimerHandle = null;
- }
- if (worker.currentWorkItem) {
- worker.currentWorkItem.reject(Error("explicitly terminated"));
- worker.currentWorkItem = null;
- }
- worker.w = null;
- }
- }
- }
-
- stop(): void {
- this.terminateWorkers();
- this.stopped = true;
- }
-
- /**
- * Start a worker (if not started) and set as busy.
- */
- wake(ws: WorkerState, work: WorkItem): void {
- if (this.stopped) {
- logger.trace("cryptoApi is stopped");
- return;
- }
- if (ws.currentWorkItem !== null) {
- throw Error("assertion failed");
- }
- ws.currentWorkItem = work;
- this.numBusy++;
- let worker: CryptoWorker;
- if (!ws.w) {
- worker = this.workerFactory.startWorker();
- worker.onmessage = (m: MessageEvent) => this.handleWorkerMessage(ws, m);
- worker.onerror = (e: ErrorEvent) => this.handleWorkerError(ws, e);
- ws.w = worker;
- } else {
- worker = ws.w;
- }
-
- const msg: any = {
- args: work.args,
- id: work.rpcId,
- operation: work.operation,
- };
- this.resetWorkerTimeout(ws);
- work.startTime = timer.performanceNow();
- setTimeout(() => worker.postMessage(msg), 0);
- }
-
- resetWorkerTimeout(ws: WorkerState): void {
- if (ws.terminationTimerHandle !== null) {
- ws.terminationTimerHandle.clear();
- ws.terminationTimerHandle = null;
- }
- const destroy = (): void => {
- // terminate worker if it's idle
- if (ws.w && ws.currentWorkItem === null) {
- ws.w.terminate();
- ws.w = null;
- }
- };
- ws.terminationTimerHandle = timer.after(15 * 1000, destroy);
- }
-
- handleWorkerError(ws: WorkerState, e: ErrorEvent): void {
- if (ws.currentWorkItem) {
- console.error(
- `error in worker during ${ws.currentWorkItem.operation}`,
- e,
- );
- } else {
- console.error("error in worker", e);
- }
- console.error(e.message);
- try {
- if (ws.w) {
- ws.w.terminate();
- ws.w = null;
- }
- } catch (e) {
- console.error(e);
- }
- if (ws.currentWorkItem !== null) {
- ws.currentWorkItem.reject(e);
- ws.currentWorkItem = null;
- this.numBusy--;
- }
- this.findWork(ws);
- }
-
- private findWork(ws: WorkerState): void {
- // try to find more work for this worker
- for (let i = 0; i < NUM_PRIO; i++) {
- const q = this.workQueues[NUM_PRIO - i - 1];
- if (q.length !== 0) {
- const work: WorkItem | undefined = q.shift();
- if (!work) {
- continue;
- }
- this.wake(ws, work);
- return;
- }
- }
- }
-
- handleWorkerMessage(ws: WorkerState, msg: MessageEvent): void {
- const id = msg.data.id;
- if (typeof id !== "number") {
- console.error("rpc id must be number");
- return;
- }
- const currentWorkItem = ws.currentWorkItem;
- ws.currentWorkItem = null;
- this.numBusy--;
- this.findWork(ws);
- if (!currentWorkItem) {
- console.error("unsolicited response from worker");
- return;
- }
- if (id !== currentWorkItem.rpcId) {
- console.error(`RPC with id ${id} has no registry entry`);
- return;
- }
-
- currentWorkItem.resolve(msg.data.result);
- }
-
- constructor(workerFactory: CryptoWorkerFactory) {
- this.workerFactory = workerFactory;
- this.workers = new Array<WorkerState>(workerFactory.getConcurrency());
-
- for (let i = 0; i < this.workers.length; i++) {
- this.workers[i] = {
- currentWorkItem: null,
- terminationTimerHandle: null,
- w: null,
- };
- }
-
- this.workQueues = [];
- for (let i = 0; i < NUM_PRIO; i++) {
- this.workQueues.push([]);
- }
- }
-
- private doRpc<T>(
- operation: string,
- priority: number,
- ...args: any[]
- ): Promise<T> {
- const p: Promise<T> = new Promise<T>((resolve, reject) => {
- const rpcId = this.nextRpcId++;
- const workItem: WorkItem = {
- operation,
- args,
- resolve,
- reject,
- rpcId,
- startTime: 0,
- };
-
- if (this.numBusy === this.workers.length) {
- const q = this.workQueues[priority];
- if (!q) {
- throw Error("assertion failed");
- }
- this.workQueues[priority].push(workItem);
- return;
- }
-
- for (const ws of this.workers) {
- if (ws.currentWorkItem !== null) {
- continue;
- }
- this.wake(ws, workItem);
- return;
- }
-
- throw Error("assertion failed");
- });
-
- return p;
- }
-
- createPlanchet(
- req: PlanchetCreationRequest,
- ): Promise<PlanchetCreationResult> {
- return this.doRpc<PlanchetCreationResult>("createPlanchet", 1, req);
- }
-
- createTipPlanchet(denom: DenominationRecord): Promise<TipPlanchet> {
- return this.doRpc<TipPlanchet>("createTipPlanchet", 1, denom);
- }
-
- hashString(str: string): Promise<string> {
- return this.doRpc<string>("hashString", 1, str);
- }
-
- hashEncoded(encodedBytes: string): Promise<string> {
- return this.doRpc<string>("hashEncoded", 1, encodedBytes);
- }
-
- isValidDenom(denom: DenominationRecord, masterPub: string): Promise<boolean> {
- return this.doRpc<boolean>("isValidDenom", 2, denom, masterPub);
- }
-
- isValidWireFee(
- type: string,
- wf: WireFee,
- masterPub: string,
- ): Promise<boolean> {
- return this.doRpc<boolean>("isValidWireFee", 2, type, wf, masterPub);
- }
-
- isValidPaymentSignature(
- sig: string,
- contractHash: string,
- merchantPub: string,
- ): Promise<boolean> {
- return this.doRpc<boolean>(
- "isValidPaymentSignature",
- 1,
- sig,
- contractHash,
- merchantPub,
- );
- }
-
- signDepositPermission(
- depositInfo: DepositInfo,
- ): Promise<CoinDepositPermission> {
- return this.doRpc<CoinDepositPermission>(
- "signDepositPermission",
- 3,
- depositInfo,
- );
- }
-
- createEddsaKeypair(): Promise<{ priv: string; pub: string }> {
- return this.doRpc<{ priv: string; pub: string }>("createEddsaKeypair", 1);
- }
-
- rsaUnblind(sig: string, bk: string, pk: string): Promise<string> {
- return this.doRpc<string>("rsaUnblind", 4, sig, bk, pk);
- }
-
- rsaVerify(hm: string, sig: string, pk: string): Promise<boolean> {
- return this.doRpc<boolean>("rsaVerify", 4, hm, sig, pk);
- }
-
- isValidWireAccount(
- paytoUri: string,
- sig: string,
- masterPub: string,
- ): Promise<boolean> {
- return this.doRpc<boolean>(
- "isValidWireAccount",
- 4,
- paytoUri,
- sig,
- masterPub,
- );
- }
-
- createRecoupRequest(coin: CoinRecord): Promise<RecoupRequest> {
- return this.doRpc<RecoupRequest>("createRecoupRequest", 1, coin);
- }
-
- createRefreshSession(
- exchangeBaseUrl: string,
- kappa: number,
- meltCoin: CoinRecord,
- newCoinDenoms: DenominationSelectionInfo,
- meltFee: AmountJson,
- ): Promise<RefreshSessionRecord> {
- return this.doRpc<RefreshSessionRecord>(
- "createRefreshSession",
- 4,
- exchangeBaseUrl,
- kappa,
- meltCoin,
- newCoinDenoms,
- meltFee,
- );
- }
-
- signCoinLink(
- oldCoinPriv: string,
- newDenomHash: string,
- oldCoinPub: string,
- transferPub: string,
- coinEv: string,
- ): Promise<string> {
- return this.doRpc<string>(
- "signCoinLink",
- 4,
- oldCoinPriv,
- newDenomHash,
- oldCoinPub,
- transferPub,
- coinEv,
- );
- }
-
- benchmark(repetitions: number): Promise<BenchmarkResult> {
- return this.doRpc<BenchmarkResult>("benchmark", 1, repetitions);
- }
-}
diff --git a/src/crypto/workers/cryptoImplementation.ts b/src/crypto/workers/cryptoImplementation.ts
deleted file mode 100644
index 979fe41d8..000000000
--- a/src/crypto/workers/cryptoImplementation.ts
+++ /dev/null
@@ -1,581 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2019-2020 Taler Systems SA
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Synchronous implementation of crypto-related functions for the wallet.
- *
- * The functionality is parameterized over an Emscripten environment.
- *
- * @author Florian Dold <dold@taler.net>
- */
-
-/**
- * Imports.
- */
-
-import {
- CoinRecord,
- DenominationRecord,
- RefreshPlanchetRecord,
- RefreshSessionRecord,
- TipPlanchet,
- WireFee,
- CoinSourceType,
- DenominationSelectionInfo,
-} from "../../types/dbTypes";
-
-import { CoinDepositPermission, RecoupRequest } from "../../types/talerTypes";
-import {
- BenchmarkResult,
- PlanchetCreationResult,
- PlanchetCreationRequest,
- DepositInfo,
-} from "../../types/walletTypes";
-import { AmountJson, Amounts } from "../../util/amounts";
-import * as timer from "../../util/timer";
-import {
- encodeCrock,
- decodeCrock,
- createEddsaKeyPair,
- createBlindingKeySecret,
- hash,
- rsaBlind,
- eddsaVerify,
- eddsaSign,
- rsaUnblind,
- stringToBytes,
- createHashContext,
- createEcdheKeyPair,
- keyExchangeEcdheEddsa,
- setupRefreshPlanchet,
- rsaVerify,
-} from "../talerCrypto";
-import { randomBytes } from "../primitives/nacl-fast";
-import { kdf } from "../primitives/kdf";
-import {
- Timestamp,
- getTimestampNow,
- timestampTruncateToSecond,
-} from "../../util/time";
-
-enum SignaturePurpose {
- WALLET_RESERVE_WITHDRAW = 1200,
- WALLET_COIN_DEPOSIT = 1201,
- MASTER_DENOMINATION_KEY_VALIDITY = 1025,
- MASTER_WIRE_FEES = 1028,
- MASTER_WIRE_DETAILS = 1030,
- WALLET_COIN_MELT = 1202,
- TEST = 4242,
- MERCHANT_PAYMENT_OK = 1104,
- WALLET_COIN_RECOUP = 1203,
- WALLET_COIN_LINK = 1204,
- EXCHANGE_CONFIRM_RECOUP = 1039,
- EXCHANGE_CONFIRM_RECOUP_REFRESH = 1041,
-}
-
-function amountToBuffer(amount: AmountJson): Uint8Array {
- const buffer = new ArrayBuffer(8 + 4 + 12);
- const dvbuf = new DataView(buffer);
- const u8buf = new Uint8Array(buffer);
- const te = new TextEncoder();
- const curr = te.encode(amount.currency);
- dvbuf.setBigUint64(0, BigInt(amount.value));
- dvbuf.setUint32(8, amount.fraction);
- u8buf.set(curr, 8 + 4);
-
- return u8buf;
-}
-
-function timestampRoundedToBuffer(ts: Timestamp): Uint8Array {
- const b = new ArrayBuffer(8);
- const v = new DataView(b);
- const tsRounded = timestampTruncateToSecond(ts);
- const s = BigInt(tsRounded.t_ms) * BigInt(1000);
- v.setBigUint64(0, s);
- return new Uint8Array(b);
-}
-
-class SignaturePurposeBuilder {
- private chunks: Uint8Array[] = [];
-
- constructor(private purposeNum: number) {}
-
- put(bytes: Uint8Array): SignaturePurposeBuilder {
- this.chunks.push(Uint8Array.from(bytes));
- return this;
- }
-
- build(): Uint8Array {
- let payloadLen = 0;
- for (const c of this.chunks) {
- payloadLen += c.byteLength;
- }
- const buf = new ArrayBuffer(4 + 4 + payloadLen);
- const u8buf = new Uint8Array(buf);
- let p = 8;
- for (const c of this.chunks) {
- u8buf.set(c, p);
- p += c.byteLength;
- }
- const dvbuf = new DataView(buf);
- dvbuf.setUint32(0, payloadLen + 4 + 4);
- dvbuf.setUint32(4, this.purposeNum);
- return u8buf;
- }
-}
-
-function buildSigPS(purposeNum: number): SignaturePurposeBuilder {
- return new SignaturePurposeBuilder(purposeNum);
-}
-
-export class CryptoImplementation {
- static enableTracing = false;
-
- /**
- * Create a pre-coin of the given denomination to be withdrawn from then given
- * reserve.
- */
- createPlanchet(req: PlanchetCreationRequest): PlanchetCreationResult {
- const reservePub = decodeCrock(req.reservePub);
- const reservePriv = decodeCrock(req.reservePriv);
- const denomPub = decodeCrock(req.denomPub);
- const coinKeyPair = createEddsaKeyPair();
- const blindingFactor = createBlindingKeySecret();
- const coinPubHash = hash(coinKeyPair.eddsaPub);
- const ev = rsaBlind(coinPubHash, blindingFactor, denomPub);
- const amountWithFee = Amounts.add(req.value, req.feeWithdraw).amount;
- const denomPubHash = hash(denomPub);
- const evHash = hash(ev);
-
- const withdrawRequest = buildSigPS(SignaturePurpose.WALLET_RESERVE_WITHDRAW)
- .put(reservePub)
- .put(amountToBuffer(amountWithFee))
- .put(denomPubHash)
- .put(evHash)
- .build();
-
- const sig = eddsaSign(withdrawRequest, reservePriv);
-
- const planchet: PlanchetCreationResult = {
- blindingKey: encodeCrock(blindingFactor),
- coinEv: encodeCrock(ev),
- coinPriv: encodeCrock(coinKeyPair.eddsaPriv),
- coinPub: encodeCrock(coinKeyPair.eddsaPub),
- coinValue: req.value,
- denomPub: encodeCrock(denomPub),
- denomPubHash: encodeCrock(denomPubHash),
- reservePub: encodeCrock(reservePub),
- withdrawSig: encodeCrock(sig),
- coinEvHash: encodeCrock(evHash),
- };
- return planchet;
- }
-
- /**
- * Create a planchet used for tipping, including the private keys.
- */
- createTipPlanchet(denom: DenominationRecord): TipPlanchet {
- const denomPub = decodeCrock(denom.denomPub);
- const coinKeyPair = createEddsaKeyPair();
- const blindingFactor = createBlindingKeySecret();
- const coinPubHash = hash(coinKeyPair.eddsaPub);
- const ev = rsaBlind(coinPubHash, blindingFactor, denomPub);
-
- const tipPlanchet: TipPlanchet = {
- blindingKey: encodeCrock(blindingFactor),
- coinEv: encodeCrock(ev),
- coinPriv: encodeCrock(coinKeyPair.eddsaPriv),
- coinPub: encodeCrock(coinKeyPair.eddsaPub),
- coinValue: denom.value,
- denomPub: encodeCrock(denomPub),
- denomPubHash: encodeCrock(hash(denomPub)),
- };
- return tipPlanchet;
- }
-
- /**
- * Create and sign a message to recoup a coin.
- */
- createRecoupRequest(coin: CoinRecord): RecoupRequest {
- const p = buildSigPS(SignaturePurpose.WALLET_COIN_RECOUP)
- .put(decodeCrock(coin.coinPub))
- .put(decodeCrock(coin.denomPubHash))
- .put(decodeCrock(coin.blindingKey))
- .build();
-
- const coinPriv = decodeCrock(coin.coinPriv);
- const coinSig = eddsaSign(p, coinPriv);
- const paybackRequest: RecoupRequest = {
- coin_blind_key_secret: coin.blindingKey,
- coin_pub: coin.coinPub,
- coin_sig: encodeCrock(coinSig),
- denom_pub_hash: coin.denomPubHash,
- denom_sig: coin.denomSig,
- refreshed: coin.coinSource.type === CoinSourceType.Refresh,
- };
- return paybackRequest;
- }
-
- /**
- * Check if a payment signature is valid.
- */
- isValidPaymentSignature(
- sig: string,
- contractHash: string,
- merchantPub: string,
- ): boolean {
- const p = buildSigPS(SignaturePurpose.MERCHANT_PAYMENT_OK)
- .put(decodeCrock(contractHash))
- .build();
- const sigBytes = decodeCrock(sig);
- const pubBytes = decodeCrock(merchantPub);
- return eddsaVerify(p, sigBytes, pubBytes);
- }
-
- /**
- * Check if a wire fee is correctly signed.
- */
- isValidWireFee(type: string, wf: WireFee, masterPub: string): boolean {
- const p = buildSigPS(SignaturePurpose.MASTER_WIRE_FEES)
- .put(hash(stringToBytes(type + "\0")))
- .put(timestampRoundedToBuffer(wf.startStamp))
- .put(timestampRoundedToBuffer(wf.endStamp))
- .put(amountToBuffer(wf.wireFee))
- .put(amountToBuffer(wf.closingFee))
- .build();
- const sig = decodeCrock(wf.sig);
- const pub = decodeCrock(masterPub);
- return eddsaVerify(p, sig, pub);
- }
-
- /**
- * Check if the signature of a denomination is valid.
- */
- isValidDenom(denom: DenominationRecord, masterPub: string): boolean {
- const p = buildSigPS(SignaturePurpose.MASTER_DENOMINATION_KEY_VALIDITY)
- .put(decodeCrock(masterPub))
- .put(timestampRoundedToBuffer(denom.stampStart))
- .put(timestampRoundedToBuffer(denom.stampExpireWithdraw))
- .put(timestampRoundedToBuffer(denom.stampExpireDeposit))
- .put(timestampRoundedToBuffer(denom.stampExpireLegal))
- .put(amountToBuffer(denom.value))
- .put(amountToBuffer(denom.feeWithdraw))
- .put(amountToBuffer(denom.feeDeposit))
- .put(amountToBuffer(denom.feeRefresh))
- .put(amountToBuffer(denom.feeRefund))
- .put(decodeCrock(denom.denomPubHash))
- .build();
- const sig = decodeCrock(denom.masterSig);
- const pub = decodeCrock(masterPub);
- return eddsaVerify(p, sig, pub);
- }
-
- isValidWireAccount(
- paytoUri: string,
- sig: string,
- masterPub: string,
- ): boolean {
- const h = kdf(
- 64,
- stringToBytes("exchange-wire-signature"),
- stringToBytes(paytoUri + "\0"),
- new Uint8Array(0),
- );
- const p = buildSigPS(SignaturePurpose.MASTER_WIRE_DETAILS).put(h).build();
- return eddsaVerify(p, decodeCrock(sig), decodeCrock(masterPub));
- }
-
- /**
- * Create a new EdDSA key pair.
- */
- createEddsaKeypair(): { priv: string; pub: string } {
- const pair = createEddsaKeyPair();
- return {
- priv: encodeCrock(pair.eddsaPriv),
- pub: encodeCrock(pair.eddsaPub),
- };
- }
-
- /**
- * Unblind a blindly signed value.
- */
- rsaUnblind(blindedSig: string, bk: string, pk: string): string {
- const denomSig = rsaUnblind(
- decodeCrock(blindedSig),
- decodeCrock(pk),
- decodeCrock(bk),
- );
- return encodeCrock(denomSig);
- }
-
- /**
- * Unblind a blindly signed value.
- */
- rsaVerify(hm: string, sig: string, pk: string): boolean {
- return rsaVerify(hash(decodeCrock(hm)), decodeCrock(sig), decodeCrock(pk));
- }
-
- /**
- * Generate updated coins (to store in the database)
- * and deposit permissions for each given coin.
- */
- signDepositPermission(depositInfo: DepositInfo): CoinDepositPermission {
- const d = buildSigPS(SignaturePurpose.WALLET_COIN_DEPOSIT)
- .put(decodeCrock(depositInfo.contractTermsHash))
- .put(decodeCrock(depositInfo.wireInfoHash))
- .put(decodeCrock(depositInfo.denomPubHash))
- .put(timestampRoundedToBuffer(depositInfo.timestamp))
- .put(timestampRoundedToBuffer(depositInfo.refundDeadline))
- .put(amountToBuffer(depositInfo.spendAmount))
- .put(amountToBuffer(depositInfo.feeDeposit))
- .put(decodeCrock(depositInfo.merchantPub))
- .put(decodeCrock(depositInfo.coinPub))
- .build();
- const coinSig = eddsaSign(d, decodeCrock(depositInfo.coinPriv));
-
- const s: CoinDepositPermission = {
- coin_pub: depositInfo.coinPub,
- coin_sig: encodeCrock(coinSig),
- contribution: Amounts.stringify(depositInfo.spendAmount),
- h_denom: depositInfo.denomPubHash,
- exchange_url: depositInfo.exchangeBaseUrl,
- ub_sig: depositInfo.denomSig,
- };
- return s;
- }
-
- /**
- * Create a new refresh session.
- */
- createRefreshSession(
- exchangeBaseUrl: string,
- kappa: number,
- meltCoin: CoinRecord,
- newCoinDenoms: DenominationSelectionInfo,
- meltFee: AmountJson,
- ): RefreshSessionRecord {
- const currency = newCoinDenoms.selectedDenoms[0].denom.value.currency;
- let valueWithFee = Amounts.getZero(currency);
-
- for (const ncd of newCoinDenoms.selectedDenoms) {
- const t = Amounts.add(ncd.denom.value, ncd.denom.feeWithdraw).amount;
- valueWithFee = Amounts.add(
- valueWithFee,
- Amounts.mult(t, ncd.count).amount,
- ).amount;
- }
-
- // melt fee
- valueWithFee = Amounts.add(valueWithFee, meltFee).amount;
-
- const sessionHc = createHashContext();
-
- const transferPubs: string[] = [];
- const transferPrivs: string[] = [];
-
- const planchetsForGammas: RefreshPlanchetRecord[][] = [];
-
- for (let i = 0; i < kappa; i++) {
- const transferKeyPair = createEcdheKeyPair();
- sessionHc.update(transferKeyPair.ecdhePub);
- transferPrivs.push(encodeCrock(transferKeyPair.ecdhePriv));
- transferPubs.push(encodeCrock(transferKeyPair.ecdhePub));
- }
-
- for (const denomSel of newCoinDenoms.selectedDenoms) {
- for (let i = 0; i < denomSel.count; i++) {
- const r = decodeCrock(denomSel.denom.denomPub);
- sessionHc.update(r);
- }
- }
-
- sessionHc.update(decodeCrock(meltCoin.coinPub));
- sessionHc.update(amountToBuffer(valueWithFee));
-
- for (let i = 0; i < kappa; i++) {
- const planchets: RefreshPlanchetRecord[] = [];
- for (let j = 0; j < newCoinDenoms.selectedDenoms.length; j++) {
- const denomSel = newCoinDenoms.selectedDenoms[j];
- for (let k = 0; k < denomSel.count; k++) {
- const coinNumber = planchets.length;
- const transferPriv = decodeCrock(transferPrivs[i]);
- const oldCoinPub = decodeCrock(meltCoin.coinPub);
- const transferSecret = keyExchangeEcdheEddsa(
- transferPriv,
- oldCoinPub,
- );
- const fresh = setupRefreshPlanchet(transferSecret, coinNumber);
- const coinPriv = fresh.coinPriv;
- const coinPub = fresh.coinPub;
- const blindingFactor = fresh.bks;
- const pubHash = hash(coinPub);
- const denomPub = decodeCrock(denomSel.denom.denomPub);
- const ev = rsaBlind(pubHash, blindingFactor, denomPub);
- const planchet: RefreshPlanchetRecord = {
- blindingKey: encodeCrock(blindingFactor),
- coinEv: encodeCrock(ev),
- privateKey: encodeCrock(coinPriv),
- publicKey: encodeCrock(coinPub),
- };
- planchets.push(planchet);
- sessionHc.update(ev);
- }
- }
- planchetsForGammas.push(planchets);
- }
-
- const sessionHash = sessionHc.finish();
-
- const confirmData = buildSigPS(SignaturePurpose.WALLET_COIN_MELT)
- .put(sessionHash)
- .put(decodeCrock(meltCoin.denomPubHash))
- .put(amountToBuffer(valueWithFee))
- .put(amountToBuffer(meltFee))
- .put(decodeCrock(meltCoin.coinPub))
- .build();
-
- const confirmSig = eddsaSign(confirmData, decodeCrock(meltCoin.coinPriv));
-
- let valueOutput = Amounts.getZero(currency);
- for (const denomSel of newCoinDenoms.selectedDenoms) {
- const denom = denomSel.denom;
- for (let i = 0; i < denomSel.count; i++) {
- valueOutput = Amounts.add(valueOutput, denom.value).amount;
- }
- }
-
- const newDenoms: string[] = [];
- const newDenomHashes: string[] = [];
-
- for (const denomSel of newCoinDenoms.selectedDenoms) {
- const denom = denomSel.denom;
- for (let i = 0; i < denomSel.count; i++) {
- newDenoms.push(denom.denomPub);
- newDenomHashes.push(denom.denomPubHash);
- }
- }
-
- const refreshSession: RefreshSessionRecord = {
- confirmSig: encodeCrock(confirmSig),
- exchangeBaseUrl,
- hash: encodeCrock(sessionHash),
- meltCoinPub: meltCoin.coinPub,
- newDenomHashes,
- newDenoms,
- norevealIndex: undefined,
- planchetsForGammas: planchetsForGammas,
- transferPrivs,
- transferPubs,
- amountRefreshOutput: valueOutput,
- amountRefreshInput: valueWithFee,
- timestampCreated: getTimestampNow(),
- finishedTimestamp: undefined,
- lastError: undefined,
- };
-
- return refreshSession;
- }
-
- /**
- * Hash a string including the zero terminator.
- */
- hashString(str: string): string {
- const ts = new TextEncoder();
- const b = ts.encode(str + "\0");
- return encodeCrock(hash(b));
- }
-
- /**
- * Hash a crockford encoded value.
- */
- hashEncoded(encodedBytes: string): string {
- return encodeCrock(hash(decodeCrock(encodedBytes)));
- }
-
- signCoinLink(
- oldCoinPriv: string,
- newDenomHash: string,
- oldCoinPub: string,
- transferPub: string,
- coinEv: string,
- ): string {
- const coinEvHash = hash(decodeCrock(coinEv));
- const coinLink = buildSigPS(SignaturePurpose.WALLET_COIN_LINK)
- .put(decodeCrock(newDenomHash))
- .put(decodeCrock(oldCoinPub))
- .put(decodeCrock(transferPub))
- .put(coinEvHash)
- .build();
- const coinPriv = decodeCrock(oldCoinPriv);
- const sig = eddsaSign(coinLink, coinPriv);
- return encodeCrock(sig);
- }
-
- benchmark(repetitions: number): BenchmarkResult {
- let time_hash = 0;
- for (let i = 0; i < repetitions; i++) {
- const start = timer.performanceNow();
- this.hashString("hello world");
- time_hash += timer.performanceNow() - start;
- }
-
- let time_hash_big = 0;
- for (let i = 0; i < repetitions; i++) {
- const ba = randomBytes(4096);
- const start = timer.performanceNow();
- hash(ba);
- time_hash_big += timer.performanceNow() - start;
- }
-
- let time_eddsa_create = 0;
- for (let i = 0; i < repetitions; i++) {
- const start = timer.performanceNow();
- createEddsaKeyPair();
- time_eddsa_create += timer.performanceNow() - start;
- }
-
- let time_eddsa_sign = 0;
- const p = randomBytes(4096);
-
- const pair = createEddsaKeyPair();
-
- for (let i = 0; i < repetitions; i++) {
- const start = timer.performanceNow();
- eddsaSign(p, pair.eddsaPriv);
- time_eddsa_sign += timer.performanceNow() - start;
- }
-
- const sig = eddsaSign(p, pair.eddsaPriv);
-
- let time_eddsa_verify = 0;
- for (let i = 0; i < repetitions; i++) {
- const start = timer.performanceNow();
- eddsaVerify(p, sig, pair.eddsaPub);
- time_eddsa_verify += timer.performanceNow() - start;
- }
-
- return {
- repetitions,
- time: {
- hash_small: time_hash,
- hash_big: time_hash_big,
- eddsa_create: time_eddsa_create,
- eddsa_sign: time_eddsa_sign,
- eddsa_verify: time_eddsa_verify,
- },
- };
- }
-}
diff --git a/src/crypto/workers/cryptoWorker.ts b/src/crypto/workers/cryptoWorker.ts
deleted file mode 100644
index 9f3ee6f50..000000000
--- a/src/crypto/workers/cryptoWorker.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-export interface CryptoWorker {
- postMessage(message: any): void;
-
- terminate(): void;
-
- onmessage: ((m: any) => void) | undefined;
- onerror: ((m: any) => void) | undefined;
-}
diff --git a/src/crypto/workers/nodeThreadWorker.ts b/src/crypto/workers/nodeThreadWorker.ts
deleted file mode 100644
index 6c9dfc569..000000000
--- a/src/crypto/workers/nodeThreadWorker.ts
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Imports
- */
-import { CryptoWorkerFactory } from "./cryptoApi";
-import { CryptoWorker } from "./cryptoWorker";
-import os from "os";
-import { CryptoImplementation } from "./cryptoImplementation";
-
-const f = __filename;
-
-const workerCode = `
- // Try loading the glue library for Android
- try {
- require("akono");
- } catch (e) {
- // Probably we're not on Android ...
- }
- const worker_threads = require('worker_threads');
- const parentPort = worker_threads.parentPort;
- let tw;
- try {
- tw = require("${f}");
- } catch (e) {
- console.log("could not load from ${f}");
- }
- if (!tw) {
- try {
- tw = require("taler-wallet-android");
- } catch (e) {
- console.log("could not load taler-wallet-android either");
- throw e;
- }
- }
- parentPort.on("message", tw.handleWorkerMessage);
- parentPort.on("error", tw.handleWorkerError);
-`;
-
-/**
- * This function is executed in the worker thread to handle
- * a message.
- */
-export function handleWorkerMessage(msg: any): void {
- const args = msg.args;
- if (!Array.isArray(args)) {
- console.error("args must be array");
- return;
- }
- const id = msg.id;
- if (typeof id !== "number") {
- console.error("RPC id must be number");
- return;
- }
- const operation = msg.operation;
- if (typeof operation !== "string") {
- console.error("RPC operation must be string");
- return;
- }
-
- const handleRequest = async (): Promise<void> => {
- const impl = new CryptoImplementation();
-
- if (!(operation in impl)) {
- console.error(`crypto operation '${operation}' not found`);
- return;
- }
-
- try {
- const result = (impl as any)[operation](...args);
- // eslint-disable-next-line @typescript-eslint/no-var-requires
- const worker_threads = require("worker_threads");
- const p = worker_threads.parentPort;
- worker_threads.parentPort?.postMessage;
- if (p) {
- p.postMessage({ data: { result, id } });
- } else {
- console.error("parent port not available (not running in thread?");
- }
- } catch (e) {
- console.error("error during operation", e);
- return;
- }
- };
-
- handleRequest().catch((e) => {
- console.error("error in node worker", e);
- });
-}
-
-export function handleWorkerError(e: Error): void {
- console.log("got error from worker", e);
-}
-
-export class NodeThreadCryptoWorkerFactory implements CryptoWorkerFactory {
- startWorker(): CryptoWorker {
- if (typeof require === "undefined") {
- throw Error("cannot make worker, require(...) not defined");
- }
- return new NodeThreadCryptoWorker();
- }
-
- getConcurrency(): number {
- return Math.max(1, os.cpus().length - 1);
- }
-}
-
-/**
- * Worker implementation that uses node subprocesses.
- */
-class NodeThreadCryptoWorker implements CryptoWorker {
- /**
- * Function to be called when we receive a message from the worker thread.
- */
- onmessage: undefined | ((m: any) => void);
-
- /**
- * Function to be called when we receive an error from the worker thread.
- */
- onerror: undefined | ((m: any) => void);
-
- private nodeWorker: import("worker_threads").Worker;
-
- constructor() {
- // eslint-disable-next-line @typescript-eslint/no-var-requires
- const worker_threads = require("worker_threads");
- this.nodeWorker = new worker_threads.Worker(workerCode, { eval: true });
- this.nodeWorker.on("error", (err: Error) => {
- console.error("error in node worker:", err);
- if (this.onerror) {
- this.onerror(err);
- }
- });
- this.nodeWorker.on("message", (v: any) => {
- if (this.onmessage) {
- this.onmessage(v);
- }
- });
- this.nodeWorker.unref();
- }
-
- /**
- * Add an event listener for either an "error" or "message" event.
- */
- addEventListener(event: "message" | "error", fn: (x: any) => void): void {
- switch (event) {
- case "message":
- this.onmessage = fn;
- break;
- case "error":
- this.onerror = fn;
- break;
- }
- }
-
- /**
- * Send a message to the worker thread.
- */
- postMessage(msg: any): void {
- this.nodeWorker.postMessage(msg);
- }
-
- /**
- * Forcibly terminate the worker thread.
- */
- terminate(): void {
- this.nodeWorker.terminate();
- }
-}
diff --git a/src/crypto/workers/synchronousWorker.ts b/src/crypto/workers/synchronousWorker.ts
deleted file mode 100644
index 2cc740975..000000000
--- a/src/crypto/workers/synchronousWorker.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- 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 { CryptoImplementation } from "./cryptoImplementation";
-
-import { CryptoWorkerFactory } from "./cryptoApi";
-import { CryptoWorker } from "./cryptoWorker";
-
-/**
- * The synchronous crypto worker produced by this factory doesn't run in the
- * background, but actually blocks the caller until the operation is done.
- */
-export class SynchronousCryptoWorkerFactory implements CryptoWorkerFactory {
- startWorker(): CryptoWorker {
- if (typeof require === "undefined") {
- throw Error("cannot make worker, require(...) not defined");
- }
- const workerCtor = require("./synchronousWorker").SynchronousCryptoWorker;
- return new workerCtor();
- }
-
- getConcurrency(): number {
- return 1;
- }
-}
-
-/**
- * Worker implementation that uses node subprocesses.
- */
-export class SynchronousCryptoWorker {
- /**
- * Function to be called when we receive a message from the worker thread.
- */
- onmessage: undefined | ((m: any) => void);
-
- /**
- * Function to be called when we receive an error from the worker thread.
- */
- onerror: undefined | ((m: any) => void);
-
- constructor() {
- this.onerror = undefined;
- this.onmessage = undefined;
- }
-
- /**
- * Add an event listener for either an "error" or "message" event.
- */
- addEventListener(event: "message" | "error", fn: (x: any) => void): void {
- switch (event) {
- case "message":
- this.onmessage = fn;
- break;
- case "error":
- this.onerror = fn;
- break;
- }
- }
-
- private dispatchMessage(msg: any): void {
- if (this.onmessage) {
- this.onmessage({ data: msg });
- }
- }
-
- private async handleRequest(
- operation: string,
- id: number,
- args: string[],
- ): Promise<void> {
- const impl = new CryptoImplementation();
-
- if (!(operation in impl)) {
- console.error(`crypto operation '${operation}' not found`);
- return;
- }
-
- let result: any;
- try {
- result = (impl as any)[operation](...args);
- } catch (e) {
- console.log("error during operation", e);
- return;
- }
-
- try {
- setTimeout(() => this.dispatchMessage({ result, id }), 0);
- } catch (e) {
- console.log("got error during dispatch", e);
- }
- }
-
- /**
- * Send a message to the worker thread.
- */
- postMessage(msg: any): void {
- const args = msg.args;
- if (!Array.isArray(args)) {
- console.error("args must be array");
- return;
- }
- const id = msg.id;
- if (typeof id !== "number") {
- console.error("RPC id must be number");
- return;
- }
- const operation = msg.operation;
- if (typeof operation !== "string") {
- console.error("RPC operation must be string");
- return;
- }
-
- this.handleRequest(operation, id, args).catch((e) => {
- console.error("Error while handling crypto request:", e);
- });
- }
-
- /**
- * Forcibly terminate the worker thread.
- */
- terminate(): void {
- // This is a no-op.
- }
-}
diff --git a/src/db.ts b/src/db.ts
deleted file mode 100644
index 5571c869c..000000000
--- a/src/db.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { Stores } from "./types/dbTypes";
-import { openDatabase, Database, Store, Index } from "./util/query";
-
-/**
- * Name of the Taler database. The name includes the
- * major version of the DB schema. The version should be incremented
- * with each major change. When incrementing the major version,
- * the wallet should import data from the previous version.
- */
-const TALER_DB_NAME = "taler-walletdb-v7";
-
-/**
- * Current database minor version, should be incremented
- * each time we do minor schema changes on the database.
- * A change is considered minor when fields are added in a
- * backwards-compatible way or object stores and indices
- * are added.
- */
-export const WALLET_DB_MINOR_VERSION = 1;
-
-/**
- * Return a promise that resolves
- * to the taler wallet db.
- */
-export function openTalerDatabase(
- idbFactory: IDBFactory,
- onVersionChange: () => void,
-): Promise<IDBDatabase> {
- const onUpgradeNeeded = (
- db: IDBDatabase,
- oldVersion: number,
- newVersion: number,
- ): void => {
- switch (oldVersion) {
- case 0: // DB does not exist yet
- for (const n in Stores) {
- if ((Stores as any)[n] instanceof Store) {
- const si: Store<any> = (Stores as any)[n];
- const s = db.createObjectStore(si.name, si.storeParams);
- for (const indexName in si as any) {
- if ((si as any)[indexName] instanceof Index) {
- const ii: Index<any, any> = (si as any)[indexName];
- s.createIndex(ii.indexName, ii.keyPath, ii.options);
- }
- }
- }
- }
- break;
- default:
- throw Error("unsupported existig DB version");
- }
- };
-
- return openDatabase(
- idbFactory,
- TALER_DB_NAME,
- WALLET_DB_MINOR_VERSION,
- onVersionChange,
- onUpgradeNeeded,
- );
-}
-
-export function deleteTalerDatabase(idbFactory: IDBFactory): void {
- Database.deleteDatabase(idbFactory, TALER_DB_NAME);
-}
diff --git a/src/headless/NodeHttpLib.ts b/src/headless/NodeHttpLib.ts
deleted file mode 100644
index d109c3b7c..000000000
--- a/src/headless/NodeHttpLib.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- 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/>
-
- SPDX-License-Identifier: AGPL3.0-or-later
-*/
-
-/**
- * Imports.
- */
-import {
- Headers,
- HttpRequestLibrary,
- HttpRequestOptions,
- HttpResponse,
-} from "../util/http";
-import { RequestThrottler } from "../util/RequestThrottler";
-import Axios from "axios";
-import { OperationFailedError, makeErrorDetails } from "../operations/errors";
-import { TalerErrorCode } from "../TalerErrorCode";
-
-/**
- * Implementation of the HTTP request library interface for node.
- */
-export class NodeHttpLib implements HttpRequestLibrary {
- private throttle = new RequestThrottler();
- private throttlingEnabled = true;
-
- /**
- * Set whether requests should be throttled.
- */
- setThrottling(enabled: boolean): void {
- this.throttlingEnabled = enabled;
- }
-
- private async req(
- method: "post" | "get",
- url: string,
- body: any,
- opt?: HttpRequestOptions,
- ): Promise<HttpResponse> {
- if (this.throttlingEnabled && this.throttle.applyThrottle(url)) {
- throw Error("request throttled");
- }
- const resp = await Axios({
- method,
- url: url,
- responseType: "text",
- headers: opt?.headers,
- validateStatus: () => true,
- transformResponse: (x) => x,
- data: body,
- });
-
- const respText = resp.data;
- if (typeof respText !== "string") {
- throw new OperationFailedError(
- makeErrorDetails(
- TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE,
- "unexpected response type",
- {
- httpStatusCode: resp.status,
- requestUrl: url,
- },
- ),
- );
- }
- const makeJson = async (): Promise<any> => {
- let responseJson;
- try {
- responseJson = JSON.parse(respText);
- } catch (e) {
- throw new OperationFailedError(
- makeErrorDetails(
- TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE,
- "invalid JSON",
- {
- httpStatusCode: resp.status,
- requestUrl: url,
- },
- ),
- );
- }
- if (responseJson === null || typeof responseJson !== "object") {
- throw new OperationFailedError(
- makeErrorDetails(
- TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE,
- "invalid JSON",
- {
- httpStatusCode: resp.status,
- requestUrl: url,
- },
- ),
- );
- }
- return responseJson;
- };
- const headers = new Headers();
- for (const hn of Object.keys(resp.headers)) {
- headers.set(hn, resp.headers[hn]);
- }
- return {
- requestUrl: url,
- headers,
- status: resp.status,
- text: async () => resp.data,
- json: makeJson,
- };
- }
-
- async get(url: string, opt?: HttpRequestOptions): Promise<HttpResponse> {
- return this.req("get", url, undefined, opt);
- }
-
- async postJson(
- url: string,
- body: any,
- opt?: HttpRequestOptions,
- ): Promise<HttpResponse> {
- return this.req("post", url, body, opt);
- }
-}
diff --git a/src/headless/clk.ts b/src/headless/clk.ts
deleted file mode 100644
index a905464bd..000000000
--- a/src/headless/clk.ts
+++ /dev/null
@@ -1,614 +0,0 @@
-/*
- 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/>
- */
-
-/**
- * Imports.
- */
-import process from "process";
-import path from "path";
-import readline from "readline";
-
-class Converter<T> {}
-
-export const INT = new Converter<number>();
-export const STRING: Converter<string> = new Converter<string>();
-
-export interface OptionArgs<T> {
- help?: string;
- default?: T;
- onPresentHandler?: (v: T) => void;
-}
-
-export interface ArgumentArgs<T> {
- metavar?: string;
- help?: string;
- default?: T;
-}
-
-export interface SubcommandArgs {
- help?: string;
-}
-
-export interface FlagArgs {
- help?: string;
-}
-
-export interface ProgramArgs {
- help?: string;
-}
-
-interface ArgumentDef {
- name: string;
- conv: Converter<any>;
- args: ArgumentArgs<any>;
- required: boolean;
-}
-
-interface SubcommandDef {
- commandGroup: CommandGroup<any, any>;
- name: string;
- args: SubcommandArgs;
-}
-
-type ActionFn<TG> = (x: TG) => void;
-
-type SubRecord<S extends keyof any, N extends keyof any, V> = {
- [Y in S]: { [X in N]: V };
-};
-
-interface OptionDef {
- name: string;
- flagspec: string[];
- /**
- * Converter, only present for options, not for flags.
- */
- conv?: Converter<any>;
- args: OptionArgs<any>;
- isFlag: boolean;
- required: boolean;
-}
-
-function splitOpt(opt: string): { key: string; value?: string } {
- const idx = opt.indexOf("=");
- if (idx == -1) {
- return { key: opt };
- }
- return { key: opt.substring(0, idx), value: opt.substring(idx + 1) };
-}
-
-function formatListing(key: string, value?: string): string {
- const res = " " + key;
- if (!value) {
- return res;
- }
- if (res.length >= 25) {
- return res + "\n" + " " + value;
- } else {
- return res.padEnd(24) + " " + value;
- }
-}
-
-export class CommandGroup<GN extends keyof any, TG> {
- private shortOptions: { [name: string]: OptionDef } = {};
- private longOptions: { [name: string]: OptionDef } = {};
- private subcommandMap: { [name: string]: SubcommandDef } = {};
- private subcommands: SubcommandDef[] = [];
- private options: OptionDef[] = [];
- private arguments: ArgumentDef[] = [];
-
- private myAction?: ActionFn<TG>;
-
- constructor(
- private argKey: string,
- private name: string | null,
- private scArgs: SubcommandArgs,
- ) {}
-
- action(f: ActionFn<TG>): void {
- if (this.myAction) {
- throw Error("only one action supported per command");
- }
- this.myAction = f;
- }
-
- requiredOption<N extends keyof any, V>(
- name: N,
- flagspec: string[],
- conv: Converter<V>,
- args: OptionArgs<V> = {},
- ): CommandGroup<GN, TG & SubRecord<GN, N, V>> {
- const def: OptionDef = {
- args: args,
- conv: conv,
- flagspec: flagspec,
- isFlag: false,
- required: true,
- name: name as string,
- };
- this.options.push(def);
- for (const flag of flagspec) {
- if (flag.startsWith("--")) {
- const flagname = flag.substring(2);
- this.longOptions[flagname] = def;
- } else if (flag.startsWith("-")) {
- const flagname = flag.substring(1);
- this.shortOptions[flagname] = def;
- } else {
- throw Error("option must start with '-' or '--'");
- }
- }
- return this as any;
- }
-
- maybeOption<N extends keyof any, V>(
- name: N,
- flagspec: string[],
- conv: Converter<V>,
- args: OptionArgs<V> = {},
- ): CommandGroup<GN, TG & SubRecord<GN, N, V | undefined>> {
- const def: OptionDef = {
- args: args,
- conv: conv,
- flagspec: flagspec,
- isFlag: false,
- required: false,
- name: name as string,
- };
- this.options.push(def);
- for (const flag of flagspec) {
- if (flag.startsWith("--")) {
- const flagname = flag.substring(2);
- this.longOptions[flagname] = def;
- } else if (flag.startsWith("-")) {
- const flagname = flag.substring(1);
- this.shortOptions[flagname] = def;
- } else {
- throw Error("option must start with '-' or '--'");
- }
- }
- return this as any;
- }
-
- requiredArgument<N extends keyof any, V>(
- name: N,
- conv: Converter<V>,
- args: ArgumentArgs<V> = {},
- ): CommandGroup<GN, TG & SubRecord<GN, N, V>> {
- const argDef: ArgumentDef = {
- args: args,
- conv: conv,
- name: name as string,
- required: true,
- };
- this.arguments.push(argDef);
- return this as any;
- }
-
- maybeArgument<N extends keyof any, V>(
- name: N,
- conv: Converter<V>,
- args: ArgumentArgs<V> = {},
- ): CommandGroup<GN, TG & SubRecord<GN, N, V | undefined>> {
- const argDef: ArgumentDef = {
- args: args,
- conv: conv,
- name: name as string,
- required: false,
- };
- this.arguments.push(argDef);
- return this as any;
- }
-
- flag<N extends string, V>(
- name: N,
- flagspec: string[],
- args: OptionArgs<V> = {},
- ): CommandGroup<GN, TG & SubRecord<GN, N, boolean>> {
- const def: OptionDef = {
- args: args,
- flagspec: flagspec,
- isFlag: true,
- required: false,
- name: name as string,
- };
- this.options.push(def);
- for (const flag of flagspec) {
- if (flag.startsWith("--")) {
- const flagname = flag.substring(2);
- this.longOptions[flagname] = def;
- } else if (flag.startsWith("-")) {
- const flagname = flag.substring(1);
- this.shortOptions[flagname] = def;
- } else {
- throw Error("option must start with '-' or '--'");
- }
- }
- return this as any;
- }
-
- subcommand<GN extends keyof any>(
- argKey: GN,
- name: string,
- args: SubcommandArgs = {},
- ): CommandGroup<GN, TG> {
- const cg = new CommandGroup<GN, {}>(argKey as string, name, args);
- const def: SubcommandDef = {
- commandGroup: cg,
- name: name as string,
- args: args,
- };
- cg.flag("help", ["-h", "--help"], {
- help: "Show this message and exit.",
- });
- this.subcommandMap[name as string] = def;
- this.subcommands.push(def);
- this.subcommands = this.subcommands.sort((x1, x2) => {
- const a = x1.name;
- const b = x2.name;
- if (a === b) {
- return 0;
- } else if (a < b) {
- return -1;
- } else {
- return 1;
- }
- });
- return cg as any;
- }
-
- printHelp(progName: string, parents: CommandGroup<any, any>[]): void {
- let usageSpec = "";
- for (const p of parents) {
- usageSpec += (p.name ?? progName) + " ";
- if (p.arguments.length >= 1) {
- usageSpec += "<ARGS...> ";
- }
- }
- usageSpec += (this.name ?? progName) + " ";
- if (this.subcommands.length != 0) {
- usageSpec += "COMMAND ";
- }
- for (const a of this.arguments) {
- const argName = a.args.metavar ?? a.name;
- usageSpec += `<${argName}> `;
- }
- usageSpec = usageSpec.trimRight();
- console.log(`Usage: ${usageSpec}`);
- if (this.scArgs.help) {
- console.log();
- console.log(this.scArgs.help);
- }
- if (this.options.length != 0) {
- console.log();
- console.log("Options:");
- for (const opt of this.options) {
- let optSpec = opt.flagspec.join(", ");
- if (!opt.isFlag) {
- optSpec = optSpec + "=VALUE";
- }
- console.log(formatListing(optSpec, opt.args.help));
- }
- }
-
- if (this.subcommands.length != 0) {
- console.log();
- console.log("Commands:");
- for (const subcmd of this.subcommands) {
- console.log(formatListing(subcmd.name, subcmd.args.help));
- }
- }
- }
-
- /**
- * Run the (sub-)command with the given command line parameters.
- */
- run(
- progname: string,
- parents: CommandGroup<any, any>[],
- unparsedArgs: string[],
- parsedArgs: any,
- ): void {
- let posArgIndex = 0;
- let argsTerminated = false;
- let i;
- let foundSubcommand: CommandGroup<any, any> | undefined = undefined;
- const myArgs: any = (parsedArgs[this.argKey] = {});
- const foundOptions: { [name: string]: boolean } = {};
- const currentName = this.name ?? progname;
- for (i = 0; i < unparsedArgs.length; i++) {
- const argVal = unparsedArgs[i];
- if (argsTerminated == false) {
- if (argVal === "--") {
- argsTerminated = true;
- continue;
- }
- if (argVal.startsWith("--")) {
- const opt = argVal.substring(2);
- const r = splitOpt(opt);
- const d = this.longOptions[r.key];
- if (!d) {
- console.error(
- `error: unknown option '--${r.key}' for ${currentName}`,
- );
- process.exit(-1);
- throw Error("not reached");
- }
- if (d.isFlag) {
- if (r.value !== undefined) {
- console.error(`error: flag '--${r.key}' does not take a value`);
- process.exit(-1);
- throw Error("not reached");
- }
- foundOptions[d.name] = true;
- myArgs[d.name] = true;
- } else {
- if (r.value === undefined) {
- if (i === unparsedArgs.length - 1) {
- console.error(`error: option '--${r.key}' needs an argument`);
- process.exit(-1);
- throw Error("not reached");
- }
- myArgs[d.name] = unparsedArgs[i + 1];
- i++;
- } else {
- myArgs[d.name] = r.value;
- }
- foundOptions[d.name] = true;
- }
- continue;
- }
- if (argVal.startsWith("-") && argVal != "-") {
- const optShort = argVal.substring(1);
- for (let si = 0; si < optShort.length; si++) {
- const chr = optShort[si];
- const opt = this.shortOptions[chr];
- if (!opt) {
- console.error(`error: option '-${chr}' not known`);
- process.exit(-1);
- }
- if (opt.isFlag) {
- myArgs[opt.name] = true;
- foundOptions[opt.name] = true;
- } else {
- if (si == optShort.length - 1) {
- if (i === unparsedArgs.length - 1) {
- console.error(`error: option '-${chr}' needs an argument`);
- process.exit(-1);
- throw Error("not reached");
- } else {
- myArgs[opt.name] = unparsedArgs[i + 1];
- i++;
- }
- } else {
- myArgs[opt.name] = optShort.substring(si + 1);
- }
- foundOptions[opt.name] = true;
- break;
- }
- }
- continue;
- }
- }
- if (this.subcommands.length != 0) {
- const subcmd = this.subcommandMap[argVal];
- if (!subcmd) {
- console.error(`error: unknown command '${argVal}'`);
- process.exit(-1);
- throw Error("not reached");
- }
- foundSubcommand = subcmd.commandGroup;
- break;
- } else {
- const d = this.arguments[posArgIndex];
- if (!d) {
- console.error(`error: too many arguments for ${currentName}`);
- process.exit(-1);
- throw Error("not reached");
- }
- myArgs[d.name] = unparsedArgs[i];
- posArgIndex++;
- }
- }
-
- if (parsedArgs[this.argKey].help) {
- this.printHelp(progname, parents);
- process.exit(0);
- throw Error("not reached");
- }
-
- for (let i = posArgIndex; i < this.arguments.length; i++) {
- const d = this.arguments[i];
- if (d.required) {
- if (d.args.default !== undefined) {
- myArgs[d.name] = d.args.default;
- } else {
- console.error(
- `error: missing positional argument '${d.name}' for ${currentName}`,
- );
- process.exit(-1);
- throw Error("not reached");
- }
- }
- }
-
- for (const option of this.options) {
- if (option.isFlag == false && option.required == true) {
- if (!foundOptions[option.name]) {
- if (option.args.default !== undefined) {
- myArgs[option.name] = option.args.default;
- } else {
- const name = option.flagspec.join(",");
- console.error(`error: missing option '${name}'`);
- process.exit(-1);
- throw Error("not reached");
- }
- }
- }
- }
-
- for (const option of this.options) {
- const ph = option.args.onPresentHandler;
- if (ph && foundOptions[option.name]) {
- ph(myArgs[option.name]);
- }
- }
-
- if (foundSubcommand) {
- foundSubcommand.run(
- progname,
- Array.prototype.concat(parents, [this]),
- unparsedArgs.slice(i + 1),
- parsedArgs,
- );
- } else if (this.myAction) {
- let r;
- try {
- r = this.myAction(parsedArgs);
- } catch (e) {
- console.error(`An error occured while running ${currentName}`);
- console.error(e);
- process.exit(1);
- }
- Promise.resolve(r).catch((e) => {
- console.error(`An error occured while running ${currentName}`);
- console.error(e);
- process.exit(1);
- });
- } else {
- this.printHelp(progname, parents);
- process.exit(-1);
- throw Error("not reached");
- }
- }
-}
-
-export class Program<PN extends keyof any, T> {
- private mainCommand: CommandGroup<any, any>;
-
- constructor(argKey: string, args: ProgramArgs = {}) {
- this.mainCommand = new CommandGroup<any, any>(argKey, null, {
- help: args.help,
- });
- this.mainCommand.flag("help", ["-h", "--help"], {
- help: "Show this message and exit.",
- });
- }
-
- run(): void {
- const args = process.argv;
- if (args.length < 2) {
- console.error(
- "Error while parsing command line arguments: not enough arguments",
- );
- process.exit(-1);
- }
- const progname = path.basename(args[1]);
- const rest = args.slice(2);
-
- this.mainCommand.run(progname, [], rest, {});
- }
-
- subcommand<GN extends keyof any>(
- argKey: GN,
- name: string,
- args: SubcommandArgs = {},
- ): CommandGroup<GN, T> {
- const cmd = this.mainCommand.subcommand(argKey, name as string, args);
- return cmd as any;
- }
-
- requiredOption<N extends keyof any, V>(
- name: N,
- flagspec: string[],
- conv: Converter<V>,
- args: OptionArgs<V> = {},
- ): Program<PN, T & SubRecord<PN, N, V>> {
- this.mainCommand.requiredOption(name, flagspec, conv, args);
- return this as any;
- }
-
- maybeOption<N extends keyof any, V>(
- name: N,
- flagspec: string[],
- conv: Converter<V>,
- args: OptionArgs<V> = {},
- ): Program<PN, T & SubRecord<PN, N, V | undefined>> {
- this.mainCommand.maybeOption(name, flagspec, conv, args);
- return this as any;
- }
-
- /**
- * Add a flag (option without value) to the program.
- */
- flag<N extends string>(
- name: N,
- flagspec: string[],
- args: OptionArgs<boolean> = {},
- ): Program<PN, T & SubRecord<PN, N, boolean>> {
- this.mainCommand.flag(name, flagspec, args);
- return this as any;
- }
-
- /**
- * Add a required positional argument to the program.
- */
- requiredArgument<N extends keyof any, V>(
- name: N,
- conv: Converter<V>,
- args: ArgumentArgs<V> = {},
- ): Program<N, T & SubRecord<PN, N, V>> {
- this.mainCommand.requiredArgument(name, conv, args);
- return this as any;
- }
-
- /**
- * Add an optional argument to the program.
- */
- maybeArgument<N extends keyof any, V>(
- name: N,
- conv: Converter<V>,
- args: ArgumentArgs<V> = {},
- ): Program<N, T & SubRecord<PN, N, V | undefined>> {
- this.mainCommand.maybeArgument(name, conv, args);
- return this as any;
- }
-}
-
-export type GetArgType<T> = T extends Program<any, infer AT>
- ? AT
- : T extends CommandGroup<any, infer AT>
- ? AT
- : any;
-
-export function program<PN extends keyof any>(
- argKey: PN,
- args: ProgramArgs = {},
-): Program<PN, {}> {
- return new Program(argKey as string, args);
-}
-
-export function prompt(question: string): Promise<string> {
- const stdinReadline = readline.createInterface({
- input: process.stdin,
- output: process.stdout,
- });
- return new Promise<string>((resolve, reject) => {
- stdinReadline.question(question, (res) => {
- resolve(res);
- stdinReadline.close();
- });
- });
-}
diff --git a/src/headless/helpers.ts b/src/headless/helpers.ts
deleted file mode 100644
index 570ec9e69..000000000
--- a/src/headless/helpers.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- 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/>
- */
-
-/**
- * Helpers to create headless wallets.
- * @author Florian Dold <dold@taler.net>
- */
-
-/**
- * Imports.
- */
-import { Wallet } from "../wallet";
-import { MemoryBackend, BridgeIDBFactory, shimIndexedDB } from "idb-bridge";
-import { openTalerDatabase } from "../db";
-import { HttpRequestLibrary } from "../util/http";
-import fs from "fs";
-import { NodeThreadCryptoWorkerFactory } from "../crypto/workers/nodeThreadWorker";
-import { WalletNotification } from "../types/notifications";
-import { Database } from "../util/query";
-import { NodeHttpLib } from "./NodeHttpLib";
-import { Logger } from "../util/logging";
-import { SynchronousCryptoWorkerFactory } from "../crypto/workers/synchronousWorker";
-
-const logger = new Logger("headless/helpers.ts");
-
-export interface DefaultNodeWalletArgs {
- /**
- * Location of the wallet database.
- *
- * If not specified, the wallet starts out with an empty database and
- * the wallet database is stored only in memory.
- */
- persistentStoragePath?: string;
-
- /**
- * Handler for asynchronous notifications from the wallet.
- */
- notifyHandler?: (n: WalletNotification) => void;
-
- /**
- * If specified, use this as HTTP request library instead
- * of the default one.
- */
- httpLib?: HttpRequestLibrary;
-}
-
-/**
- * Get a wallet instance with default settings for node.
- */
-export async function getDefaultNodeWallet(
- args: DefaultNodeWalletArgs = {},
-): Promise<Wallet> {
- BridgeIDBFactory.enableTracing = false;
- const myBackend = new MemoryBackend();
- myBackend.enableTracing = false;
-
- const storagePath = args.persistentStoragePath;
- if (storagePath) {
- try {
- const dbContentStr: string = fs.readFileSync(storagePath, {
- encoding: "utf-8",
- });
- const dbContent = JSON.parse(dbContentStr);
- myBackend.importDump(dbContent);
- } catch (e) {
- logger.warn("could not read wallet file");
- }
-
- myBackend.afterCommitCallback = async () => {
- // Allow caller to stop persisting the wallet.
- if (args.persistentStoragePath === undefined) {
- return;
- }
- const dbContent = myBackend.exportDump();
- fs.writeFileSync(storagePath, JSON.stringify(dbContent, undefined, 2), {
- encoding: "utf-8",
- });
- };
- }
-
- BridgeIDBFactory.enableTracing = false;
-
- const myBridgeIdbFactory = new BridgeIDBFactory(myBackend);
- const myIdbFactory: IDBFactory = (myBridgeIdbFactory as any) as IDBFactory;
-
- let myHttpLib;
- if (args.httpLib) {
- myHttpLib = args.httpLib;
- } else {
- myHttpLib = new NodeHttpLib();
- }
-
- const myVersionChange = (): Promise<void> => {
- console.error("version change requested, should not happen");
- throw Error();
- };
-
- shimIndexedDB(myBridgeIdbFactory);
-
- const myDb = await openTalerDatabase(myIdbFactory, myVersionChange);
-
- let workerFactory;
- try {
- // Try if we have worker threads available, fails in older node versions.
- require("worker_threads");
- workerFactory = new NodeThreadCryptoWorkerFactory();
- } catch (e) {
- console.log(
- "worker threads not available, falling back to synchronous workers",
- );
- workerFactory = new SynchronousCryptoWorkerFactory();
- }
-
- const dbWrap = new Database(myDb);
-
- const w = new Wallet(dbWrap, myHttpLib, workerFactory);
- if (args.notifyHandler) {
- w.addNotificationListener(args.notifyHandler);
- }
- return w;
-}
diff --git a/src/headless/taler-wallet-cli.ts b/src/headless/taler-wallet-cli.ts
deleted file mode 100644
index a7f306ec3..000000000
--- a/src/headless/taler-wallet-cli.ts
+++ /dev/null
@@ -1,658 +0,0 @@
-/*
- 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 os from "os";
-import fs from "fs";
-import { getDefaultNodeWallet } from "./helpers";
-import { Wallet } from "../wallet";
-import qrcodeGenerator from "qrcode-generator";
-import * as clk from "./clk";
-import { BridgeIDBFactory } from "idb-bridge";
-import { Logger } from "../util/logging";
-import { Amounts } from "../util/amounts";
-import {
- decodeCrock,
- setupRefreshPlanchet,
- encodeCrock,
-} from "../crypto/talerCrypto";
-import {
- OperationFailedAndReportedError,
- OperationFailedError,
-} from "../operations/errors";
-import { classifyTalerUri, TalerUriType } from "../util/taleruri";
-import { Configuration } from "../util/talerconfig";
-import { setDangerousTimetravel } from "../util/time";
-import { makeCodecForList, codecForString } from "../util/codec";
-import { NodeHttpLib } from "./NodeHttpLib";
-import * as nacl from "../crypto/primitives/nacl-fast";
-import { addPaytoQueryParams } from "../util/payto";
-import { handleCoreApiRequest } from "../walletCoreApiHandler";
-import { PreparePayResultType } from "../types/walletTypes";
-
-const logger = new Logger("taler-wallet-cli.ts");
-
-const defaultWalletDbPath = os.homedir + "/" + ".talerwalletdb.json";
-
-function assertUnreachable(x: never): never {
- throw new Error("Didn't expect to get here");
-}
-
-async function doPay(
- wallet: Wallet,
- payUrl: string,
- options: { alwaysYes: boolean } = { alwaysYes: true },
-): Promise<void> {
- const result = await wallet.preparePayForUri(payUrl);
- if (result.status === PreparePayResultType.InsufficientBalance) {
- console.log("contract", result.contractTerms);
- console.error("insufficient balance");
- process.exit(1);
- return;
- }
- if (result.status === PreparePayResultType.AlreadyConfirmed) {
- if (result.paid) {
- console.log("already paid!");
- } else {
- console.log("payment already in progress");
- }
-
- process.exit(0);
- return;
- }
- if (result.status === "payment-possible") {
- console.log("paying ...");
- } else {
- throw Error("not reached");
- }
- console.log("contract", result.contractTerms);
- console.log("raw amount:", result.amountRaw);
- console.log("effective amount:", result.amountEffective);
- 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) {
- await wallet.confirmPay(result.proposalId, undefined);
- } else {
- console.log("not paying");
- }
-}
-
-function applyVerbose(verbose: boolean): void {
- if (verbose) {
- console.log("enabled verbose logging");
- BridgeIDBFactory.enableTracing = true;
- }
-}
-
-function printVersion(): void {
- // eslint-disable-next-line @typescript-eslint/no-var-requires
- const info = require("../../../package.json");
- console.log(`${info.version}`);
- process.exit(0);
-}
-
-const walletCli = clk
- .program("wallet", {
- help: "Command line interface for the GNU Taler wallet.",
- })
- .maybeOption("walletDbFile", ["--wallet-db"], clk.STRING, {
- help: "location of the wallet database file",
- })
- .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);
- },
- })
- .maybeOption("inhibit", ["--inhibit"], clk.STRING, {
- help:
- "Inhibit running certain operations, useful for debugging and testing.",
- })
- .flag("noThrottle", ["--no-throttle"], {
- help: "Don't do any request throttling.",
- })
- .flag("version", ["-v", "--version"], {
- onPresentHandler: printVersion,
- })
- .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> {
- const dbPath = walletCliArgs.wallet.walletDbFile ?? defaultWalletDbPath;
- const myHttpLib = new NodeHttpLib();
- if (walletCliArgs.wallet.noThrottle) {
- myHttpLib.setThrottling(false);
- }
- const wallet = await getDefaultNodeWallet({
- persistentStoragePath: dbPath,
- httpLib: myHttpLib,
- });
- applyVerbose(walletCliArgs.wallet.verbose);
- try {
- await wallet.fillDefaults();
- const ret = await f(wallet);
- return ret;
- } catch (e) {
- if (
- e instanceof OperationFailedAndReportedError ||
- e instanceof OperationFailedError
- ) {
- console.error("Operation failed: " + e.message);
- console.error(
- "Error details:",
- JSON.stringify(e.operationError, undefined, 2),
- );
- } else {
- console.error("caught unhandled exception (bug?):", e);
- }
- process.exit(1);
- } finally {
- wallet.stop();
- }
-}
-
-walletCli
- .subcommand("balance", "balance", { help: "Show wallet balance." })
- .flag("json", ["--json"], {
- help: "Show raw JSON.",
- })
- .action(async (args) => {
- await withWallet(args, async (wallet) => {
- const balance = await wallet.getBalances();
- console.log(JSON.stringify(balance, undefined, 2));
- });
- });
-
-walletCli
- .subcommand("api", "api", { help: "Call the wallet-core API directly." })
- .requiredArgument("operation", clk.STRING)
- .requiredArgument("request", clk.STRING)
- .action(async (args) => {
- await withWallet(args, async (wallet) => {
- let requestJson;
- try {
- requestJson = JSON.parse(args.api.request);
- } catch (e) {
- console.error("Invalid JSON");
- process.exit(1);
- }
- const resp = await handleCoreApiRequest(
- wallet,
- args.api.operation,
- "reqid-1",
- requestJson,
- );
- console.log(JSON.stringify(resp, undefined, 2));
- });
- });
-
-walletCli
- .subcommand("", "pending", { help: "Show pending operations." })
- .action(async (args) => {
- await withWallet(args, async (wallet) => {
- const pending = await wallet.getPendingOperations();
- console.log(JSON.stringify(pending, undefined, 2));
- });
- });
-
-walletCli
- .subcommand("transactions", "transactions", { help: "Show transactions." })
- .maybeOption("currency", ["--currency"], clk.STRING)
- .maybeOption("search", ["--search"], clk.STRING)
- .action(async (args) => {
- await withWallet(args, async (wallet) => {
- const pending = await wallet.getTransactions({
- currency: args.transactions.currency,
- search: args.transactions.search,
- });
- console.log(JSON.stringify(pending, undefined, 2));
- });
- });
-
-async function asyncSleep(milliSeconds: number): Promise<void> {
- return new Promise<void>((resolve, reject) => {
- setTimeout(() => resolve(), milliSeconds);
- });
-}
-
-walletCli
- .subcommand("runPendingOpt", "run-pending", {
- help: "Run pending operations.",
- })
- .flag("forceNow", ["-f", "--force-now"])
- .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();
- });
- });
-
-walletCli
- .subcommand("handleUri", "handle-uri", {
- help: "Handle a taler:// URI.",
- })
- .requiredArgument("uri", clk.STRING)
- .flag("autoYes", ["-y", "--yes"])
- .action(async (args) => {
- await withWallet(args, async (wallet) => {
- const uri: string = args.handleUri.uri;
- 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:
- {
- const withdrawInfo = await wallet.getWithdrawalDetailsForUri(uri);
- const selectedExchange = withdrawInfo.defaultExchangeBaseUrl;
- 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;
- }
- return;
- });
- });
-
-const exchangesCli = walletCli.subcommand("exchangesCmd", "exchanges", {
- help: "Manage exchanges.",
-});
-
-exchangesCli
- .subcommand("exchangesListCmd", "list", {
- help: "List known exchanges.",
- })
- .action(async (args) => {
- console.log("Listing exchanges ...");
- await withWallet(args, async (wallet) => {
- const exchanges = await wallet.getExchanges();
- console.log(JSON.stringify(exchanges, undefined, 2));
- });
- });
-
-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"])
- .action(async (args) => {
- await withWallet(args, async (wallet) => {
- await wallet.updateExchangeFromUrl(
- 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) => {
- 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,
- args.exchangesAcceptTosCmd.etag,
- );
- });
- });
-
-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) => {
- const tosResult = await wallet.getExchangeTos(args.exchangesTosCmd.url);
- console.log(JSON.stringify(tosResult, undefined, 2));
- });
- });
-
-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) => {
- const details = await wallet.getWithdrawalDetailsForAmount(
- args.manualWithdrawalDetails.exchange,
- Amounts.parseOrThrow(args.manualWithdrawalDetails.amount),
- );
- console.log(JSON.stringify(details, undefined, 2));
- });
- });
-
-advancedCli
- .subcommand("decode", "decode", {
- help: "Decode base32-crockford.",
- })
- .action((args) => {
- const enc = fs.readFileSync(0, "utf8");
- fs.writeFileSync(1, decodeCrock(enc.trim()));
- });
-
-advancedCli
- .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;
- }
- const reserve = await wallet.acceptManualWithdrawal(
- exchange.baseUrl,
- Amounts.parseOrThrow(args.withdrawManually.amount),
- );
- 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);
- });
- });
-
-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);
- });
- });
-
-advancedCli
- .subcommand("payPrepare", "pay-prepare", {
- help: "Claim an order but don't pay yet.",
- })
- .requiredArgument("url", clk.STRING)
- .action(async (args) => {
- await withWallet(args, async (wallet) => {
- const res = await wallet.preparePayForUri(args.payPrepare.url);
- switch (res.status) {
- case PreparePayResultType.InsufficientBalance:
- console.log("insufficient balance");
- break;
- case PreparePayResultType.AlreadyConfirmed:
- if (res.paid) {
- console.log("already paid!");
- } else {
- console.log("payment in progress");
- }
- break;
- case PreparePayResultType.PaymentPossible:
- console.log("payment possible");
- break;
- default:
- assertUnreachable(res);
- }
- });
- });
-
-advancedCli
- .subcommand("payConfirm", "pay-confirm", {
- help: "Confirm payment proposed by a merchant.",
- })
- .requiredArgument("proposalId", clk.STRING)
- .maybeOption("sessionIdOverride", ["--session-id"], clk.STRING)
- .action(async (args) => {
- await withWallet(args, async (wallet) => {
- wallet.confirmPay(
- args.payConfirm.proposalId,
- args.payConfirm.sessionIdOverride,
- );
- });
- });
-
-advancedCli
- .subcommand("refresh", "force-refresh", {
- help: "Force a refresh on a coin.",
- })
- .requiredArgument("coinPub", clk.STRING)
- .action(async (args) => {
- await withWallet(args, async (wallet) => {
- await wallet.refresh(args.refresh.coinPub);
- });
- });
-
-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));
- });
- });
-
-const coinPubListCodec = makeCodecForList(codecForString);
-
-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);
- }
- });
- });
-
-advancedCli
- .subcommand("coins", "list-coins", {
- help: "List coins.",
- })
- .action(async (args) => {
- await withWallet(args, async (wallet) => {
- 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}`);
- console.log(
- ` remaining amount ${Amounts.stringify(coin.currentAmount)}`,
- );
- }
- });
- });
-
-advancedCli
- .subcommand("updateReserve", "update-reserve", {
- help: "Update reserve status.",
- })
- .requiredArgument("reservePub", clk.STRING)
- .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)
- .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));
- });
- });
-
-const testCli = walletCli.subcommand("testingArgs", "testing", {
- help: "Subcommands for testing GNU Taler deployments.",
-});
-
-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)}`);
-});
-
-walletCli.run();
diff --git a/src/i18n/de.po b/src/i18n/de.po
deleted file mode 100644
index bb355403d..000000000
--- a/src/i18n/de.po
+++ /dev/null
@@ -1,363 +0,0 @@
-# This file is part of TALER
-# (C) 2016 GNUnet e.V.
-#
-# 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.
-#
-# 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
-# TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
-#
-#, fuzzy
-msgid ""
-msgstr ""
-"Project-Id-Version: Taler Wallet\n"
-"Report-Msgid-Bugs-To: \n"
-"POT-Creation-Date: 2016-11-23 00:00+0100\n"
-"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
-"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
-"Language-Team: LANGUAGE <LL@li.org>\n"
-"Language: \n"
-"MIME-Version: 1.0\n"
-"Content-Type: text/plain; charset=UTF-8\n"
-"Content-Transfer-Encoding: 8bit\n"
-"Plural-Forms: nplurals=2; plural=(n != 1);\n"
-
-#: src/util/wire.ts:37
-#, c-format
-msgid "Invalid Wire"
-msgstr ""
-
-#: src/util/wire.ts:42 src/util/wire.ts:45
-#, c-format
-msgid "Invalid Test Wire Detail"
-msgstr ""
-
-#: src/util/wire.ts:47
-#, c-format
-msgid "Test Wire Acct #%1$s on %2$s"
-msgstr ""
-
-#: src/util/wire.ts:49
-#, c-format
-msgid "Unknown Wire Detail"
-msgstr ""
-
-#: src/webex/pages/benchmark.tsx:52
-#, c-format
-msgid "Operation"
-msgstr ""
-
-#: src/webex/pages/benchmark.tsx:53
-#, c-format
-msgid "time (ms/op)"
-msgstr ""
-
-#: src/webex/pages/pay.tsx:130
-#, fuzzy, c-format
-msgid "The merchant %1$s offers you to purchase:"
-msgstr "Der Händler %1$s möchte einen Vertrag über %2$s mit Ihnen abschließen."
-
-#: src/webex/pages/pay.tsx:136
-#, c-format
-msgid "The total price is %1$s (plus %2$s fees)."
-msgstr ""
-
-#: src/webex/pages/pay.tsx:141
-#, c-format
-msgid "The total price is %1$s."
-msgstr ""
-
-#: src/webex/pages/pay.tsx:163
-#, c-format
-msgid "Retry"
-msgstr ""
-
-#: src/webex/pages/pay.tsx:173
-#, fuzzy, c-format
-msgid "Confirm payment"
-msgstr "Bezahlung bestätigen"
-
-#: src/webex/pages/popup.tsx:153
-#, c-format
-msgid "Balance"
-msgstr "Saldo"
-
-#: src/webex/pages/popup.tsx:154
-#, c-format
-msgid "History"
-msgstr "Verlauf"
-
-#: src/webex/pages/popup.tsx:155
-#, c-format
-msgid "Debug"
-msgstr "Debug"
-
-#: src/webex/pages/popup.tsx:175
-#, fuzzy, c-format
-msgid "You have no balance to show. Need some %1$s getting started?"
-msgstr "Sie haben kein Digitalgeld. Wollen Sie %1$s? abheben?"
-
-#: src/webex/pages/popup.tsx:238
-#, c-format
-msgid "%1$s incoming"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:250
-#, c-format
-msgid "%1$s being spent"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:281
-#, c-format
-msgid "Error: could not retrieve balance information."
-msgstr ""
-
-#: src/webex/pages/popup.tsx:390
-#, c-format
-msgid "Invalid "
-msgstr ""
-
-#: src/webex/pages/popup.tsx:396
-#, c-format
-msgid "Fees "
-msgstr ""
-
-#: src/webex/pages/popup.tsx:434
-#, c-format
-msgid "Refresh sessions has completed"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:451
-#, c-format
-msgid "Order Refused"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:465
-#, c-format
-msgid "Order redirected"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:482
-#, c-format
-msgid "Payment aborted"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:512
-#, c-format
-msgid "Payment Sent"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:536
-#, c-format
-msgid "Order accepted"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:547
-#, c-format
-msgid "Reserve balance updated"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:559
-#, c-format
-msgid "Payment refund"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:584
-#, fuzzy, c-format
-msgid "Withdrawn"
-msgstr "Abheben bei %1$s"
-
-#: src/webex/pages/popup.tsx:596
-#, c-format
-msgid "Tip Accepted"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:606
-#, c-format
-msgid "Tip Declined"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:615
-#, c-format
-msgid "%1$s"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:707
-#, c-format
-msgid "Your wallet has no events recorded."
-msgstr "Ihre Geldbörse verzeichnet keine Vorkommnisse."
-
-#: src/webex/pages/return-coins.tsx:124
-#, c-format
-msgid "Wire to bank account"
-msgstr ""
-
-#: src/webex/pages/return-coins.tsx:206
-#, fuzzy, c-format
-msgid "Confirm"
-msgstr "Bezahlung bestätigen"
-
-#: src/webex/pages/return-coins.tsx:209
-#, fuzzy, c-format
-msgid "Cancel"
-msgstr "Saldo"
-
-#: src/webex/pages/withdraw.tsx:73
-#, c-format
-msgid "Could not get details for withdraw operation:"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:89 src/webex/pages/withdraw.tsx:183
-#, c-format
-msgid "Chose different exchange provider"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:109
-#, c-format
-msgid ""
-"Please select an exchange. You can review the details before after your "
-"selection."
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:121
-#, c-format
-msgid "Select %1$s"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:143
-#, c-format
-msgid "Select custom exchange"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:163
-#, c-format
-msgid "You are about to withdraw %1$s from your bank account into your wallet."
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:174
-#, c-format
-msgid "Accept fees and withdraw"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:192
-#, c-format
-msgid "Cancel withdraw operation"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:249
-#, fuzzy, c-format
-msgid "Withdrawal fees:"
-msgstr "Abheben bei"
-
-#: src/webex/renderHtml.tsx:252
-#, c-format
-msgid "Rounding loss:"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:254
-#, c-format
-msgid "Earliest expiration (for deposit): %1$s"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:262
-#, c-format
-msgid "# Coins"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:263
-#, c-format
-msgid "Value"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:264
-#, fuzzy, c-format
-msgid "Withdraw Fee"
-msgstr "Abheben bei %1$s"
-
-#: src/webex/renderHtml.tsx:265
-#, c-format
-msgid "Refresh Fee"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:266
-#, c-format
-msgid "Deposit Fee"
-msgstr ""
-
-#, fuzzy, c-format
-#~ msgid "Bank requested reserve (%1$s) for %2$s."
-#~ msgstr "Bank bestätig anlegen der Reserve (%1$s) bei %2$s"
-
-#, fuzzy, c-format
-#~ msgid "Started to withdraw %1$s from %2$s (%3$s)."
-#~ msgstr "Reserve (%1$s) mit %2$s bei %3$s erzeugt"
-
-#, fuzzy, c-format
-#~ msgid "Merchant %1$s offered contract %2$s."
-#~ msgstr ""
-#~ "%1$s\n"
-#~ " möchte einen Vertrag über %2$s\n"
-#~ " mit Ihnen abschließen."
-
-#, fuzzy, c-format
-#~ msgid "Withdrew %1$s from %2$s ( %3$s)."
-#~ msgstr "Reserve (%1$s) mit %2$s bei %3$s erzeugt"
-
-#, fuzzy, c-format
-#~ msgid "Paid %1$s to merchant %2$s.%3$s( %4$s)"
-#~ msgstr "Reserve (%1$s) mit %2$s bei %3$s erzeugt"
-
-#, fuzzy, c-format
-#~ msgid "Merchant %1$s gave a refund over %2$s."
-#~ msgstr ""
-#~ "%1$s\n"
-#~ " möchte einen Vertrag über %2$s\n"
-#~ " mit Ihnen abschließen."
-
-#, fuzzy, c-format
-#~ msgid "Merchant %1$s gave a %2$s of %3$s."
-#~ msgstr ""
-#~ "%1$s\n"
-#~ " möchte einen Vertrag über %2$s\n"
-#~ " mit Ihnen abschließen."
-
-#, fuzzy, c-format
-#~ msgid "Submitting payment"
-#~ msgstr "Bezahlung bestätigen"
-
-#, fuzzy, c-format
-#~ msgid "Aborting payment ..."
-#~ msgstr "Bezahlung bestätigen"
-
-#, fuzzy, c-format
-#~ msgid "Retry Payment"
-#~ msgstr "Bezahlung bestätigen"
-
-#, fuzzy, c-format
-#~ msgid "Abort Payment"
-#~ msgstr "Bezahlung bestätigen"
-
-#, fuzzy
-#~ msgid "You are about to purchase:"
-#~ msgstr "Sie sind dabei, Folgendes zu kaufen:"
-
-#, fuzzy
-#~ msgid "Withdrawal fees: %1$s"
-#~ msgstr "Abheben bei %1$s"
-
-#~ msgid "Wallet depleted reserve (%1$s) at %2$s"
-#~ msgstr "Geldbörse hat die Reserve (%1$s) erschöpft"
-
-#~ msgid "Please enter a URL"
-#~ msgstr "Bitte eine URL eingeben"
-
-#~ msgid "The URL you've entered is not valid (must be absolute)"
-#~ msgstr "Die eingegebene URL ist nicht gültig (muss absolut sein)"
-
-#~ msgid "The bank wants to create a reserve over %1$s."
-#~ msgstr "Die Bank möchte eine Reserve über %1$s anlegen."
diff --git a/src/i18n/en-US.po b/src/i18n/en-US.po
deleted file mode 100644
index 4fe38d5e9..000000000
--- a/src/i18n/en-US.po
+++ /dev/null
@@ -1,294 +0,0 @@
-# This file is part of TALER
-# (C) 2016 GNUnet e.V.
-#
-# 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.
-#
-# 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
-# TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
-#
-#, fuzzy
-msgid ""
-msgstr ""
-"Project-Id-Version: Taler Wallet\n"
-"Report-Msgid-Bugs-To: \n"
-"POT-Creation-Date: 2016-11-23 00:00+0100\n"
-"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
-"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
-"Language-Team: LANGUAGE <LL@li.org>\n"
-"Language: \n"
-"MIME-Version: 1.0\n"
-"Content-Type: text/plain; charset=UTF-8\n"
-"Content-Transfer-Encoding: 8bit\n"
-"Plural-Forms: nplurals=2; plural=(n != 1);\n"
-
-#: src/util/wire.ts:37
-#, c-format
-msgid "Invalid Wire"
-msgstr ""
-
-#: src/util/wire.ts:42 src/util/wire.ts:45
-#, c-format
-msgid "Invalid Test Wire Detail"
-msgstr ""
-
-#: src/util/wire.ts:47
-#, c-format
-msgid "Test Wire Acct #%1$s on %2$s"
-msgstr ""
-
-#: src/util/wire.ts:49
-#, c-format
-msgid "Unknown Wire Detail"
-msgstr ""
-
-#: src/webex/pages/benchmark.tsx:52
-#, c-format
-msgid "Operation"
-msgstr ""
-
-#: src/webex/pages/benchmark.tsx:53
-#, c-format
-msgid "time (ms/op)"
-msgstr ""
-
-#: src/webex/pages/pay.tsx:130
-#, c-format
-msgid "The merchant %1$s offers you to purchase:"
-msgstr ""
-
-#: src/webex/pages/pay.tsx:136
-#, c-format
-msgid "The total price is %1$s (plus %2$s fees)."
-msgstr ""
-
-#: src/webex/pages/pay.tsx:141
-#, c-format
-msgid "The total price is %1$s."
-msgstr ""
-
-#: src/webex/pages/pay.tsx:163
-#, c-format
-msgid "Retry"
-msgstr ""
-
-#: src/webex/pages/pay.tsx:173
-#, c-format
-msgid "Confirm payment"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:153
-#, c-format
-msgid "Balance"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:154
-#, c-format
-msgid "History"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:155
-#, c-format
-msgid "Debug"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:175
-#, c-format
-msgid "You have no balance to show. Need some %1$s getting started?"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:238
-#, c-format
-msgid "%1$s incoming"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:250
-#, c-format
-msgid "%1$s being spent"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:281
-#, c-format
-msgid "Error: could not retrieve balance information."
-msgstr ""
-
-#: src/webex/pages/popup.tsx:390
-#, c-format
-msgid "Invalid "
-msgstr ""
-
-#: src/webex/pages/popup.tsx:396
-#, c-format
-msgid "Fees "
-msgstr ""
-
-#: src/webex/pages/popup.tsx:434
-#, c-format
-msgid "Refresh sessions has completed"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:451
-#, c-format
-msgid "Order Refused"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:465
-#, c-format
-msgid "Order redirected"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:482
-#, c-format
-msgid "Payment aborted"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:512
-#, c-format
-msgid "Payment Sent"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:536
-#, c-format
-msgid "Order accepted"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:547
-#, c-format
-msgid "Reserve balance updated"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:559
-#, c-format
-msgid "Payment refund"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:584
-#, c-format
-msgid "Withdrawn"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:596
-#, c-format
-msgid "Tip Accepted"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:606
-#, c-format
-msgid "Tip Declined"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:615
-#, c-format
-msgid "%1$s"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:707
-#, c-format
-msgid "Your wallet has no events recorded."
-msgstr ""
-
-#: src/webex/pages/return-coins.tsx:124
-#, c-format
-msgid "Wire to bank account"
-msgstr ""
-
-#: src/webex/pages/return-coins.tsx:206
-#, c-format
-msgid "Confirm"
-msgstr ""
-
-#: src/webex/pages/return-coins.tsx:209
-#, c-format
-msgid "Cancel"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:73
-#, c-format
-msgid "Could not get details for withdraw operation:"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:89 src/webex/pages/withdraw.tsx:183
-#, c-format
-msgid "Chose different exchange provider"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:109
-#, c-format
-msgid ""
-"Please select an exchange. You can review the details before after your "
-"selection."
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:121
-#, c-format
-msgid "Select %1$s"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:143
-#, c-format
-msgid "Select custom exchange"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:163
-#, c-format
-msgid "You are about to withdraw %1$s from your bank account into your wallet."
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:174
-#, c-format
-msgid "Accept fees and withdraw"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:192
-#, c-format
-msgid "Cancel withdraw operation"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:249
-#, c-format
-msgid "Withdrawal fees:"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:252
-#, c-format
-msgid "Rounding loss:"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:254
-#, c-format
-msgid "Earliest expiration (for deposit): %1$s"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:262
-#, c-format
-msgid "# Coins"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:263
-#, c-format
-msgid "Value"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:264
-#, c-format
-msgid "Withdraw Fee"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:265
-#, c-format
-msgid "Refresh Fee"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:266
-#, c-format
-msgid "Deposit Fee"
-msgstr ""
-
-#, fuzzy
-#~ msgid "DEBUG: Your balance on %1$s is %2$s KUDO. Get more at %3$s"
-#~ msgstr "DEBUG: Your balance is %2$s KUDO on %1$s. Get more at %3$s"
diff --git a/src/i18n/fr.po b/src/i18n/fr.po
deleted file mode 100644
index 67b09de1a..000000000
--- a/src/i18n/fr.po
+++ /dev/null
@@ -1,290 +0,0 @@
-# This file is part of TALER
-# (C) 2016 GNUnet e.V.
-#
-# 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.
-#
-# 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
-# TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
-#
-#, fuzzy
-msgid ""
-msgstr ""
-"Project-Id-Version: Taler Wallet\n"
-"Report-Msgid-Bugs-To: \n"
-"POT-Creation-Date: 2016-11-23 00:00+0100\n"
-"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
-"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
-"Language-Team: LANGUAGE <LL@li.org>\n"
-"Language: \n"
-"MIME-Version: 1.0\n"
-"Content-Type: text/plain; charset=UTF-8\n"
-"Content-Transfer-Encoding: 8bit\n"
-"Plural-Forms: nplurals=2; plural=(n != 1);\n"
-
-#: src/util/wire.ts:37
-#, c-format
-msgid "Invalid Wire"
-msgstr ""
-
-#: src/util/wire.ts:42 src/util/wire.ts:45
-#, c-format
-msgid "Invalid Test Wire Detail"
-msgstr ""
-
-#: src/util/wire.ts:47
-#, c-format
-msgid "Test Wire Acct #%1$s on %2$s"
-msgstr ""
-
-#: src/util/wire.ts:49
-#, c-format
-msgid "Unknown Wire Detail"
-msgstr ""
-
-#: src/webex/pages/benchmark.tsx:52
-#, c-format
-msgid "Operation"
-msgstr ""
-
-#: src/webex/pages/benchmark.tsx:53
-#, c-format
-msgid "time (ms/op)"
-msgstr ""
-
-#: src/webex/pages/pay.tsx:130
-#, c-format
-msgid "The merchant %1$s offers you to purchase:"
-msgstr ""
-
-#: src/webex/pages/pay.tsx:136
-#, c-format
-msgid "The total price is %1$s (plus %2$s fees)."
-msgstr ""
-
-#: src/webex/pages/pay.tsx:141
-#, c-format
-msgid "The total price is %1$s."
-msgstr ""
-
-#: src/webex/pages/pay.tsx:163
-#, c-format
-msgid "Retry"
-msgstr ""
-
-#: src/webex/pages/pay.tsx:173
-#, c-format
-msgid "Confirm payment"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:153
-#, c-format
-msgid "Balance"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:154
-#, c-format
-msgid "History"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:155
-#, c-format
-msgid "Debug"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:175
-#, c-format
-msgid "You have no balance to show. Need some %1$s getting started?"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:238
-#, c-format
-msgid "%1$s incoming"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:250
-#, c-format
-msgid "%1$s being spent"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:281
-#, c-format
-msgid "Error: could not retrieve balance information."
-msgstr ""
-
-#: src/webex/pages/popup.tsx:390
-#, c-format
-msgid "Invalid "
-msgstr ""
-
-#: src/webex/pages/popup.tsx:396
-#, c-format
-msgid "Fees "
-msgstr ""
-
-#: src/webex/pages/popup.tsx:434
-#, c-format
-msgid "Refresh sessions has completed"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:451
-#, c-format
-msgid "Order Refused"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:465
-#, c-format
-msgid "Order redirected"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:482
-#, c-format
-msgid "Payment aborted"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:512
-#, c-format
-msgid "Payment Sent"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:536
-#, c-format
-msgid "Order accepted"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:547
-#, c-format
-msgid "Reserve balance updated"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:559
-#, c-format
-msgid "Payment refund"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:584
-#, c-format
-msgid "Withdrawn"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:596
-#, c-format
-msgid "Tip Accepted"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:606
-#, c-format
-msgid "Tip Declined"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:615
-#, c-format
-msgid "%1$s"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:707
-#, c-format
-msgid "Your wallet has no events recorded."
-msgstr ""
-
-#: src/webex/pages/return-coins.tsx:124
-#, c-format
-msgid "Wire to bank account"
-msgstr ""
-
-#: src/webex/pages/return-coins.tsx:206
-#, c-format
-msgid "Confirm"
-msgstr ""
-
-#: src/webex/pages/return-coins.tsx:209
-#, c-format
-msgid "Cancel"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:73
-#, c-format
-msgid "Could not get details for withdraw operation:"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:89 src/webex/pages/withdraw.tsx:183
-#, c-format
-msgid "Chose different exchange provider"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:109
-#, c-format
-msgid ""
-"Please select an exchange. You can review the details before after your "
-"selection."
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:121
-#, c-format
-msgid "Select %1$s"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:143
-#, c-format
-msgid "Select custom exchange"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:163
-#, c-format
-msgid "You are about to withdraw %1$s from your bank account into your wallet."
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:174
-#, c-format
-msgid "Accept fees and withdraw"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:192
-#, c-format
-msgid "Cancel withdraw operation"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:249
-#, c-format
-msgid "Withdrawal fees:"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:252
-#, c-format
-msgid "Rounding loss:"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:254
-#, c-format
-msgid "Earliest expiration (for deposit): %1$s"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:262
-#, c-format
-msgid "# Coins"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:263
-#, c-format
-msgid "Value"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:264
-#, c-format
-msgid "Withdraw Fee"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:265
-#, c-format
-msgid "Refresh Fee"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:266
-#, c-format
-msgid "Deposit Fee"
-msgstr ""
diff --git a/src/i18n/it.po b/src/i18n/it.po
deleted file mode 100644
index 67b09de1a..000000000
--- a/src/i18n/it.po
+++ /dev/null
@@ -1,290 +0,0 @@
-# This file is part of TALER
-# (C) 2016 GNUnet e.V.
-#
-# 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.
-#
-# 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
-# TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
-#
-#, fuzzy
-msgid ""
-msgstr ""
-"Project-Id-Version: Taler Wallet\n"
-"Report-Msgid-Bugs-To: \n"
-"POT-Creation-Date: 2016-11-23 00:00+0100\n"
-"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
-"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
-"Language-Team: LANGUAGE <LL@li.org>\n"
-"Language: \n"
-"MIME-Version: 1.0\n"
-"Content-Type: text/plain; charset=UTF-8\n"
-"Content-Transfer-Encoding: 8bit\n"
-"Plural-Forms: nplurals=2; plural=(n != 1);\n"
-
-#: src/util/wire.ts:37
-#, c-format
-msgid "Invalid Wire"
-msgstr ""
-
-#: src/util/wire.ts:42 src/util/wire.ts:45
-#, c-format
-msgid "Invalid Test Wire Detail"
-msgstr ""
-
-#: src/util/wire.ts:47
-#, c-format
-msgid "Test Wire Acct #%1$s on %2$s"
-msgstr ""
-
-#: src/util/wire.ts:49
-#, c-format
-msgid "Unknown Wire Detail"
-msgstr ""
-
-#: src/webex/pages/benchmark.tsx:52
-#, c-format
-msgid "Operation"
-msgstr ""
-
-#: src/webex/pages/benchmark.tsx:53
-#, c-format
-msgid "time (ms/op)"
-msgstr ""
-
-#: src/webex/pages/pay.tsx:130
-#, c-format
-msgid "The merchant %1$s offers you to purchase:"
-msgstr ""
-
-#: src/webex/pages/pay.tsx:136
-#, c-format
-msgid "The total price is %1$s (plus %2$s fees)."
-msgstr ""
-
-#: src/webex/pages/pay.tsx:141
-#, c-format
-msgid "The total price is %1$s."
-msgstr ""
-
-#: src/webex/pages/pay.tsx:163
-#, c-format
-msgid "Retry"
-msgstr ""
-
-#: src/webex/pages/pay.tsx:173
-#, c-format
-msgid "Confirm payment"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:153
-#, c-format
-msgid "Balance"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:154
-#, c-format
-msgid "History"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:155
-#, c-format
-msgid "Debug"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:175
-#, c-format
-msgid "You have no balance to show. Need some %1$s getting started?"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:238
-#, c-format
-msgid "%1$s incoming"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:250
-#, c-format
-msgid "%1$s being spent"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:281
-#, c-format
-msgid "Error: could not retrieve balance information."
-msgstr ""
-
-#: src/webex/pages/popup.tsx:390
-#, c-format
-msgid "Invalid "
-msgstr ""
-
-#: src/webex/pages/popup.tsx:396
-#, c-format
-msgid "Fees "
-msgstr ""
-
-#: src/webex/pages/popup.tsx:434
-#, c-format
-msgid "Refresh sessions has completed"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:451
-#, c-format
-msgid "Order Refused"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:465
-#, c-format
-msgid "Order redirected"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:482
-#, c-format
-msgid "Payment aborted"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:512
-#, c-format
-msgid "Payment Sent"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:536
-#, c-format
-msgid "Order accepted"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:547
-#, c-format
-msgid "Reserve balance updated"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:559
-#, c-format
-msgid "Payment refund"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:584
-#, c-format
-msgid "Withdrawn"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:596
-#, c-format
-msgid "Tip Accepted"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:606
-#, c-format
-msgid "Tip Declined"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:615
-#, c-format
-msgid "%1$s"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:707
-#, c-format
-msgid "Your wallet has no events recorded."
-msgstr ""
-
-#: src/webex/pages/return-coins.tsx:124
-#, c-format
-msgid "Wire to bank account"
-msgstr ""
-
-#: src/webex/pages/return-coins.tsx:206
-#, c-format
-msgid "Confirm"
-msgstr ""
-
-#: src/webex/pages/return-coins.tsx:209
-#, c-format
-msgid "Cancel"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:73
-#, c-format
-msgid "Could not get details for withdraw operation:"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:89 src/webex/pages/withdraw.tsx:183
-#, c-format
-msgid "Chose different exchange provider"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:109
-#, c-format
-msgid ""
-"Please select an exchange. You can review the details before after your "
-"selection."
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:121
-#, c-format
-msgid "Select %1$s"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:143
-#, c-format
-msgid "Select custom exchange"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:163
-#, c-format
-msgid "You are about to withdraw %1$s from your bank account into your wallet."
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:174
-#, c-format
-msgid "Accept fees and withdraw"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:192
-#, c-format
-msgid "Cancel withdraw operation"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:249
-#, c-format
-msgid "Withdrawal fees:"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:252
-#, c-format
-msgid "Rounding loss:"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:254
-#, c-format
-msgid "Earliest expiration (for deposit): %1$s"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:262
-#, c-format
-msgid "# Coins"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:263
-#, c-format
-msgid "Value"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:264
-#, c-format
-msgid "Withdraw Fee"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:265
-#, c-format
-msgid "Refresh Fee"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:266
-#, c-format
-msgid "Deposit Fee"
-msgstr ""
diff --git a/src/i18n/poheader b/src/i18n/poheader
deleted file mode 100644
index 3ec704932..000000000
--- a/src/i18n/poheader
+++ /dev/null
@@ -1,26 +0,0 @@
-# This file is part of TALER
-# (C) 2016 GNUnet e.V.
-#
-# 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.
-#
-# 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
-# TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
-#
-#, fuzzy
-msgid ""
-msgstr ""
-"Project-Id-Version: Taler Wallet\n"
-"Report-Msgid-Bugs-To: taler@gnu.org\n"
-"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
-"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
-"Language-Team: LANGUAGE <LL@li.org>\n"
-"MIME-Version: 1.0\n"
-"Content-Type: text/plain; charset=UTF-8\n"
-"Content-Transfer-Encoding: 8bit\n"
-"Plural-Forms: nplurals=2; plural=(n != 1);\n"
diff --git a/src/i18n/strings-prelude b/src/i18n/strings-prelude
deleted file mode 100644
index aa6602bd4..000000000
--- a/src/i18n/strings-prelude
+++ /dev/null
@@ -1,17 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 Inria
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-export const strings: {[s: string]: any} = {};
diff --git a/src/i18n/strings.ts b/src/i18n/strings.ts
deleted file mode 100644
index 748b9656a..000000000
--- a/src/i18n/strings.ts
+++ /dev/null
@@ -1,373 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 Inria
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-export const strings: { [s: string]: any } = {};
-strings["de"] = {
- domain: "messages",
- locale_data: {
- messages: {
- "": {
- domain: "messages",
- plural_forms: "nplurals=2; plural=(n != 1);",
- lang: "",
- },
- "Invalid Wire": [""],
- "Invalid Test Wire Detail": [""],
- "Test Wire Acct #%1$s on %2$s": [""],
- "Unknown Wire Detail": [""],
- Operation: [""],
- "time (ms/op)": [""],
- "The merchant %1$s offers you to purchase:": [
- "Der Händler %1$s möchte einen Vertrag über %2$s mit Ihnen abschließen.",
- ],
- "The total price is %1$s (plus %2$s fees).": [""],
- "The total price is %1$s.": [""],
- Retry: [""],
- "Confirm payment": ["Bezahlung bestätigen"],
- Balance: ["Saldo"],
- History: ["Verlauf"],
- Debug: ["Debug"],
- "You have no balance to show. Need some %1$s getting started?": [
- "Sie haben kein Digitalgeld. Wollen Sie %1$s? abheben?",
- ],
- "%1$s incoming": [""],
- "%1$s being spent": [""],
- "Error: could not retrieve balance information.": [""],
- "Invalid ": [""],
- "Fees ": [""],
- "Refresh sessions has completed": [""],
- "Order Refused": [""],
- "Order redirected": [""],
- "Payment aborted": [""],
- "Payment Sent": [""],
- "Order accepted": [""],
- "Reserve balance updated": [""],
- "Payment refund": [""],
- Withdrawn: ["Abheben bei %1$s"],
- "Tip Accepted": [""],
- "Tip Declined": [""],
- "%1$s": [""],
- "Your wallet has no events recorded.": [
- "Ihre Geldbörse verzeichnet keine Vorkommnisse.",
- ],
- "Wire to bank account": [""],
- Confirm: ["Bezahlung bestätigen"],
- Cancel: ["Saldo"],
- "Could not get details for withdraw operation:": [""],
- "Chose different exchange provider": [""],
- "Please select an exchange. You can review the details before after your selection.": [
- "",
- ],
- "Select %1$s": [""],
- "Select custom exchange": [""],
- "You are about to withdraw %1$s from your bank account into your wallet.": [
- "",
- ],
- "Accept fees and withdraw": [""],
- "Cancel withdraw operation": [""],
- "Withdrawal fees:": ["Abheben bei"],
- "Rounding loss:": [""],
- "Earliest expiration (for deposit): %1$s": [""],
- "# Coins": [""],
- Value: [""],
- "Withdraw Fee": ["Abheben bei %1$s"],
- "Refresh Fee": [""],
- "Deposit Fee": [""],
- },
- },
-};
-
-strings["en-US"] = {
- domain: "messages",
- locale_data: {
- messages: {
- "": {
- domain: "messages",
- plural_forms: "nplurals=2; plural=(n != 1);",
- lang: "",
- },
- "Invalid Wire": [""],
- "Invalid Test Wire Detail": [""],
- "Test Wire Acct #%1$s on %2$s": [""],
- "Unknown Wire Detail": [""],
- Operation: [""],
- "time (ms/op)": [""],
- "The merchant %1$s offers you to purchase:": [""],
- "The total price is %1$s (plus %2$s fees).": [""],
- "The total price is %1$s.": [""],
- Retry: [""],
- "Confirm payment": [""],
- Balance: [""],
- History: [""],
- Debug: [""],
- "You have no balance to show. Need some %1$s getting started?": [""],
- "%1$s incoming": [""],
- "%1$s being spent": [""],
- "Error: could not retrieve balance information.": [""],
- "Invalid ": [""],
- "Fees ": [""],
- "Refresh sessions has completed": [""],
- "Order Refused": [""],
- "Order redirected": [""],
- "Payment aborted": [""],
- "Payment Sent": [""],
- "Order accepted": [""],
- "Reserve balance updated": [""],
- "Payment refund": [""],
- Withdrawn: [""],
- "Tip Accepted": [""],
- "Tip Declined": [""],
- "%1$s": [""],
- "Your wallet has no events recorded.": [""],
- "Wire to bank account": [""],
- Confirm: [""],
- Cancel: [""],
- "Could not get details for withdraw operation:": [""],
- "Chose different exchange provider": [""],
- "Please select an exchange. You can review the details before after your selection.": [
- "",
- ],
- "Select %1$s": [""],
- "Select custom exchange": [""],
- "You are about to withdraw %1$s from your bank account into your wallet.": [
- "",
- ],
- "Accept fees and withdraw": [""],
- "Cancel withdraw operation": [""],
- "Withdrawal fees:": [""],
- "Rounding loss:": [""],
- "Earliest expiration (for deposit): %1$s": [""],
- "# Coins": [""],
- Value: [""],
- "Withdraw Fee": [""],
- "Refresh Fee": [""],
- "Deposit Fee": [""],
- },
- },
-};
-
-strings["fr"] = {
- domain: "messages",
- locale_data: {
- messages: {
- "": {
- domain: "messages",
- plural_forms: "nplurals=2; plural=(n != 1);",
- lang: "",
- },
- "Invalid Wire": [""],
- "Invalid Test Wire Detail": [""],
- "Test Wire Acct #%1$s on %2$s": [""],
- "Unknown Wire Detail": [""],
- Operation: [""],
- "time (ms/op)": [""],
- "The merchant %1$s offers you to purchase:": [""],
- "The total price is %1$s (plus %2$s fees).": [""],
- "The total price is %1$s.": [""],
- Retry: [""],
- "Confirm payment": [""],
- Balance: [""],
- History: [""],
- Debug: [""],
- "You have no balance to show. Need some %1$s getting started?": [""],
- "%1$s incoming": [""],
- "%1$s being spent": [""],
- "Error: could not retrieve balance information.": [""],
- "Invalid ": [""],
- "Fees ": [""],
- "Refresh sessions has completed": [""],
- "Order Refused": [""],
- "Order redirected": [""],
- "Payment aborted": [""],
- "Payment Sent": [""],
- "Order accepted": [""],
- "Reserve balance updated": [""],
- "Payment refund": [""],
- Withdrawn: [""],
- "Tip Accepted": [""],
- "Tip Declined": [""],
- "%1$s": [""],
- "Your wallet has no events recorded.": [""],
- "Wire to bank account": [""],
- Confirm: [""],
- Cancel: [""],
- "Could not get details for withdraw operation:": [""],
- "Chose different exchange provider": [""],
- "Please select an exchange. You can review the details before after your selection.": [
- "",
- ],
- "Select %1$s": [""],
- "Select custom exchange": [""],
- "You are about to withdraw %1$s from your bank account into your wallet.": [
- "",
- ],
- "Accept fees and withdraw": [""],
- "Cancel withdraw operation": [""],
- "Withdrawal fees:": [""],
- "Rounding loss:": [""],
- "Earliest expiration (for deposit): %1$s": [""],
- "# Coins": [""],
- Value: [""],
- "Withdraw Fee": [""],
- "Refresh Fee": [""],
- "Deposit Fee": [""],
- },
- },
-};
-
-strings["it"] = {
- domain: "messages",
- locale_data: {
- messages: {
- "": {
- domain: "messages",
- plural_forms: "nplurals=2; plural=(n != 1);",
- lang: "",
- },
- "Invalid Wire": [""],
- "Invalid Test Wire Detail": [""],
- "Test Wire Acct #%1$s on %2$s": [""],
- "Unknown Wire Detail": [""],
- Operation: [""],
- "time (ms/op)": [""],
- "The merchant %1$s offers you to purchase:": [""],
- "The total price is %1$s (plus %2$s fees).": [""],
- "The total price is %1$s.": [""],
- Retry: [""],
- "Confirm payment": [""],
- Balance: [""],
- History: [""],
- Debug: [""],
- "You have no balance to show. Need some %1$s getting started?": [""],
- "%1$s incoming": [""],
- "%1$s being spent": [""],
- "Error: could not retrieve balance information.": [""],
- "Invalid ": [""],
- "Fees ": [""],
- "Refresh sessions has completed": [""],
- "Order Refused": [""],
- "Order redirected": [""],
- "Payment aborted": [""],
- "Payment Sent": [""],
- "Order accepted": [""],
- "Reserve balance updated": [""],
- "Payment refund": [""],
- Withdrawn: [""],
- "Tip Accepted": [""],
- "Tip Declined": [""],
- "%1$s": [""],
- "Your wallet has no events recorded.": [""],
- "Wire to bank account": [""],
- Confirm: [""],
- Cancel: [""],
- "Could not get details for withdraw operation:": [""],
- "Chose different exchange provider": [""],
- "Please select an exchange. You can review the details before after your selection.": [
- "",
- ],
- "Select %1$s": [""],
- "Select custom exchange": [""],
- "You are about to withdraw %1$s from your bank account into your wallet.": [
- "",
- ],
- "Accept fees and withdraw": [""],
- "Cancel withdraw operation": [""],
- "Withdrawal fees:": [""],
- "Rounding loss:": [""],
- "Earliest expiration (for deposit): %1$s": [""],
- "# Coins": [""],
- Value: [""],
- "Withdraw Fee": [""],
- "Refresh Fee": [""],
- "Deposit Fee": [""],
- },
- },
-};
-
-strings["sv"] = {
- domain: "messages",
- locale_data: {
- messages: {
- "": {
- domain: "messages",
- plural_forms: "nplurals=2; plural=(n != 1);",
- lang: "",
- },
- "Invalid Wire": [""],
- "Invalid Test Wire Detail": [""],
- "Test Wire Acct #%1$s on %2$s": [""],
- "Unknown Wire Detail": ["visa mer"],
- Operation: [""],
- "time (ms/op)": [""],
- "The merchant %1$s offers you to purchase:": [
- "Säljaren %1$s erbjuder följande:",
- ],
- "The total price is %1$s (plus %2$s fees).": [
- "Det totala priset är %1$s (plus %2$s avgifter).\n",
- ],
- "The total price is %1$s.": ["Det totala priset är %1$s."],
- Retry: [""],
- "Confirm payment": ["Godkän betalning"],
- Balance: ["Balans"],
- History: ["Historia"],
- Debug: [""],
- "You have no balance to show. Need some %1$s getting started?": [
- "Du har ingen balans att visa. Behöver du\n %1$s att börja?\n",
- ],
- "%1$s incoming": ["%1$s inkommande"],
- "%1$s being spent": [""],
- "Error: could not retrieve balance information.": [""],
- "Invalid ": [""],
- "Fees ": [""],
- "Refresh sessions has completed": [""],
- "Order Refused": [""],
- "Order redirected": [""],
- "Payment aborted": [""],
- "Payment Sent": [""],
- "Order accepted": [""],
- "Reserve balance updated": [""],
- "Payment refund": [""],
- Withdrawn: ["Utbetalnings avgift"],
- "Tip Accepted": [""],
- "Tip Declined": [""],
- "%1$s": [""],
- "Your wallet has no events recorded.": ["plånboken"],
- "Wire to bank account": ["Övervisa till bank konto"],
- Confirm: ["Bekräfta"],
- Cancel: ["Avbryt"],
- "Could not get details for withdraw operation:": [""],
- "Chose different exchange provider": ["Ändra tjänsteleverantörer"],
- "Please select an exchange. You can review the details before after your selection.": [
- "",
- ],
- "Select %1$s": ["Välj %1$s"],
- "Select custom exchange": [""],
- "You are about to withdraw %1$s from your bank account into your wallet.": [
- "Du är på väg att ta ut\n %1$s från ditt bankkonto till din plånbok.\n",
- ],
- "Accept fees and withdraw": ["Acceptera avgifter och utbetala"],
- "Cancel withdraw operation": [""],
- "Withdrawal fees:": ["Utbetalnings avgifter:"],
- "Rounding loss:": [""],
- "Earliest expiration (for deposit): %1$s": [""],
- "# Coins": ["# Mynt"],
- Value: ["Värde"],
- "Withdraw Fee": ["Utbetalnings avgift"],
- "Refresh Fee": ["Återhämtnings avgift"],
- "Deposit Fee": ["Depostitions avgift"],
- },
- },
-};
diff --git a/src/i18n/sv.po b/src/i18n/sv.po
deleted file mode 100644
index c6a739789..000000000
--- a/src/i18n/sv.po
+++ /dev/null
@@ -1,388 +0,0 @@
-# This file is part of TALER
-# (C) 2016 GNUnet e.V.
-#
-# 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.
-#
-# 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
-# TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
-#
-#, fuzzy
-msgid ""
-msgstr ""
-"Project-Id-Version: Taler Wallet\n"
-"Report-Msgid-Bugs-To: \n"
-"POT-Creation-Date: 2016-11-23 00:00+0100\n"
-"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
-"Last-Translator: Flo Reitz <EMAIL@ADDRESS>\n"
-"Language-Team: LANGUAGE <LL@li.org>\n"
-"Language: \n"
-"MIME-Version: 1.0\n"
-"Content-Type: text/plain; charset=UTF-8\n"
-"Content-Transfer-Encoding: 8bit\n"
-"Plural-Forms: nplurals=2; plural=(n != 1);\n"
-
-#: src/util/wire.ts:37
-#, c-format
-msgid "Invalid Wire"
-msgstr ""
-
-#: src/util/wire.ts:42 src/util/wire.ts:45
-#, c-format
-msgid "Invalid Test Wire Detail"
-msgstr ""
-
-#: src/util/wire.ts:47
-#, c-format
-msgid "Test Wire Acct #%1$s on %2$s"
-msgstr ""
-
-#: src/util/wire.ts:49
-#, fuzzy, c-format
-msgid "Unknown Wire Detail"
-msgstr "visa mer"
-
-#: src/webex/pages/benchmark.tsx:52
-#, c-format
-msgid "Operation"
-msgstr ""
-
-#: src/webex/pages/benchmark.tsx:53
-#, c-format
-msgid "time (ms/op)"
-msgstr ""
-
-#: src/webex/pages/pay.tsx:130
-#, fuzzy, c-format
-msgid "The merchant %1$s offers you to purchase:"
-msgstr "Säljaren %1$s erbjuder följande:"
-
-#: src/webex/pages/pay.tsx:136
-#, fuzzy, c-format
-msgid "The total price is %1$s (plus %2$s fees)."
-msgstr "Det totala priset är %1$s (plus %2$s avgifter).\n"
-
-#: src/webex/pages/pay.tsx:141
-#, fuzzy, c-format
-msgid "The total price is %1$s."
-msgstr "Det totala priset är %1$s."
-
-#: src/webex/pages/pay.tsx:163
-#, c-format
-msgid "Retry"
-msgstr ""
-
-#: src/webex/pages/pay.tsx:173
-#, c-format
-msgid "Confirm payment"
-msgstr "Godkän betalning"
-
-#: src/webex/pages/popup.tsx:153
-#, c-format
-msgid "Balance"
-msgstr "Balans"
-
-#: src/webex/pages/popup.tsx:154
-#, c-format
-msgid "History"
-msgstr "Historia"
-
-#: src/webex/pages/popup.tsx:155
-#, c-format
-msgid "Debug"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:175
-#, fuzzy, c-format
-msgid "You have no balance to show. Need some %1$s getting started?"
-msgstr ""
-"Du har ingen balans att visa. Behöver du\n"
-" %1$s att börja?\n"
-
-#: src/webex/pages/popup.tsx:238
-#, fuzzy, c-format
-msgid "%1$s incoming"
-msgstr "%1$s inkommande"
-
-#: src/webex/pages/popup.tsx:250
-#, c-format
-msgid "%1$s being spent"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:281
-#, c-format
-msgid "Error: could not retrieve balance information."
-msgstr ""
-
-#: src/webex/pages/popup.tsx:390
-#, c-format
-msgid "Invalid "
-msgstr ""
-
-#: src/webex/pages/popup.tsx:396
-#, c-format
-msgid "Fees "
-msgstr ""
-
-#: src/webex/pages/popup.tsx:434
-#, c-format
-msgid "Refresh sessions has completed"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:451
-#, c-format
-msgid "Order Refused"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:465
-#, c-format
-msgid "Order redirected"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:482
-#, c-format
-msgid "Payment aborted"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:512
-#, c-format
-msgid "Payment Sent"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:536
-#, c-format
-msgid "Order accepted"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:547
-#, c-format
-msgid "Reserve balance updated"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:559
-#, c-format
-msgid "Payment refund"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:584
-#, fuzzy, c-format
-msgid "Withdrawn"
-msgstr "Utbetalnings avgift"
-
-#: src/webex/pages/popup.tsx:596
-#, c-format
-msgid "Tip Accepted"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:606
-#, c-format
-msgid "Tip Declined"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:615
-#, c-format
-msgid "%1$s"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:707
-#, c-format
-msgid "Your wallet has no events recorded."
-msgstr "plånboken"
-
-#: src/webex/pages/return-coins.tsx:124
-#, c-format
-msgid "Wire to bank account"
-msgstr "Övervisa till bank konto"
-
-#: src/webex/pages/return-coins.tsx:206
-#, c-format
-msgid "Confirm"
-msgstr "Bekräfta"
-
-#: src/webex/pages/return-coins.tsx:209
-#, c-format
-msgid "Cancel"
-msgstr "Avbryt"
-
-#: src/webex/pages/withdraw.tsx:73
-#, c-format
-msgid "Could not get details for withdraw operation:"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:89 src/webex/pages/withdraw.tsx:183
-#, fuzzy, c-format
-msgid "Chose different exchange provider"
-msgstr "Ändra tjänsteleverantörer"
-
-#: src/webex/pages/withdraw.tsx:109
-#, c-format
-msgid ""
-"Please select an exchange. You can review the details before after your "
-"selection."
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:121
-#, fuzzy, c-format
-msgid "Select %1$s"
-msgstr "Välj %1$s"
-
-#: src/webex/pages/withdraw.tsx:143
-#, c-format
-msgid "Select custom exchange"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:163
-#, fuzzy, c-format
-msgid "You are about to withdraw %1$s from your bank account into your wallet."
-msgstr ""
-"Du är på väg att ta ut\n"
-" %1$s från ditt bankkonto till din plånbok.\n"
-
-#: src/webex/pages/withdraw.tsx:174
-#, c-format
-msgid "Accept fees and withdraw"
-msgstr "Acceptera avgifter och utbetala"
-
-#: src/webex/pages/withdraw.tsx:192
-#, c-format
-msgid "Cancel withdraw operation"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:249
-#, c-format
-msgid "Withdrawal fees:"
-msgstr "Utbetalnings avgifter:"
-
-#: src/webex/renderHtml.tsx:252
-#, c-format
-msgid "Rounding loss:"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:254
-#, c-format
-msgid "Earliest expiration (for deposit): %1$s"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:262
-#, c-format
-msgid "# Coins"
-msgstr "# Mynt"
-
-#: src/webex/renderHtml.tsx:263
-#, c-format
-msgid "Value"
-msgstr "Värde"
-
-#: src/webex/renderHtml.tsx:264
-#, c-format
-msgid "Withdraw Fee"
-msgstr "Utbetalnings avgift"
-
-#: src/webex/renderHtml.tsx:265
-#, c-format
-msgid "Refresh Fee"
-msgstr "Återhämtnings avgift"
-
-#: src/webex/renderHtml.tsx:266
-#, c-format
-msgid "Deposit Fee"
-msgstr "Depostitions avgift"
-
-#, fuzzy, c-format
-#~ msgid "Merchant %1$s offered contract %2$s."
-#~ msgstr "Säljaren %1$s erbjöd kontrakt %2$s.\n"
-
-#, fuzzy, c-format
-#~ msgid "Merchant %1$s gave a refund over %2$s."
-#~ msgstr "Säljaren %1$sgav en återbetalning på %2$s.\n"
-
-#, fuzzy, c-format
-#~ msgid "Merchant %1$s gave a %2$s of %3$s."
-#~ msgstr "Säljaren %1$sgav en återbetalning på %2$s.\n"
-
-#, c-format
-#~ msgid "help"
-#~ msgstr "hjälp"
-
-#, c-format
-#~ msgid "Payback"
-#~ msgstr "Ã…terbetalning"
-
-#, c-format
-#~ msgid "Return Electronic Cash to Bank Account"
-#~ msgstr "Återlämna elektroniska pengar till bank konto"
-
-#, fuzzy, c-format
-#~ msgid "show more details"
-#~ msgstr "visa mer"
-
-#, c-format
-#~ msgid "Accepted exchanges:"
-#~ msgstr "Accepterade tjänsteleverantörer:"
-
-#, c-format
-#~ msgid "Exchanges in the wallet:"
-#~ msgstr "Tjänsteleverantörer i plånboken:"
-
-#, c-format
-#~ msgid ""
-#~ "You have insufficient funds of the requested currency in your wallet."
-#~ msgstr "plånboken"
-
-#, c-format
-#~ msgid ""
-#~ "You do not have any funds from an exchange that is accepted by this "
-#~ "merchant. None of the exchanges accepted by the merchant is known to your "
-#~ "wallet."
-#~ msgstr "plånboken"
-
-#, c-format
-#~ msgid "Submitting payment"
-#~ msgstr "Bekräftar betalning"
-
-#, c-format
-#~ msgid ""
-#~ "You already paid for this, clicking \"Confirm payment\" will not cost "
-#~ "money again."
-#~ msgstr ""
-#~ "Du har redan betalat för det här, om du trycker \"Godkän betalning\" "
-#~ "debiteras du inte igen"
-
-#, fuzzy, c-format
-#~ msgid "Aborting payment ..."
-#~ msgstr "Bekräftar betalning"
-
-#, fuzzy, c-format
-#~ msgid "Abort Payment"
-#~ msgstr "Godkän betalning"
-
-#, c-format
-#~ msgid "Select"
-#~ msgstr "Välj"
-
-#, fuzzy, c-format
-#~ msgid "The exchange is trusted by the wallet."
-#~ msgstr "Tjänsteleverantörer i plånboken:"
-
-#, fuzzy, c-format
-#~ msgid ""
-#~ "Your wallet (protocol version %1$s) might be outdated.%2$s The exchange "
-#~ "has a higher, incompatible protocol version (%3$s)."
-#~ msgstr "tjänsteleverantörer plånboken"
-
-#, fuzzy, c-format
-#~ msgid ""
-#~ "The chosen exchange (protocol version %1$s might be outdated.%2$s The "
-#~ "exchange has a lower, incompatible protocol version than your wallet "
-#~ "(protocol version %3$s)."
-#~ msgstr "tjänsteleverantörer plånboken"
-
-#, fuzzy, c-format
-#~ msgid ""
-#~ "Oops, something went wrong. The wallet responded with error status (%1$s)."
-#~ msgstr "plånboken"
diff --git a/src/i18n/taler-wallet-webex.pot b/src/i18n/taler-wallet-webex.pot
deleted file mode 100644
index 67b09de1a..000000000
--- a/src/i18n/taler-wallet-webex.pot
+++ /dev/null
@@ -1,290 +0,0 @@
-# This file is part of TALER
-# (C) 2016 GNUnet e.V.
-#
-# 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.
-#
-# 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
-# TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
-#
-#, fuzzy
-msgid ""
-msgstr ""
-"Project-Id-Version: Taler Wallet\n"
-"Report-Msgid-Bugs-To: \n"
-"POT-Creation-Date: 2016-11-23 00:00+0100\n"
-"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
-"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
-"Language-Team: LANGUAGE <LL@li.org>\n"
-"Language: \n"
-"MIME-Version: 1.0\n"
-"Content-Type: text/plain; charset=UTF-8\n"
-"Content-Transfer-Encoding: 8bit\n"
-"Plural-Forms: nplurals=2; plural=(n != 1);\n"
-
-#: src/util/wire.ts:37
-#, c-format
-msgid "Invalid Wire"
-msgstr ""
-
-#: src/util/wire.ts:42 src/util/wire.ts:45
-#, c-format
-msgid "Invalid Test Wire Detail"
-msgstr ""
-
-#: src/util/wire.ts:47
-#, c-format
-msgid "Test Wire Acct #%1$s on %2$s"
-msgstr ""
-
-#: src/util/wire.ts:49
-#, c-format
-msgid "Unknown Wire Detail"
-msgstr ""
-
-#: src/webex/pages/benchmark.tsx:52
-#, c-format
-msgid "Operation"
-msgstr ""
-
-#: src/webex/pages/benchmark.tsx:53
-#, c-format
-msgid "time (ms/op)"
-msgstr ""
-
-#: src/webex/pages/pay.tsx:130
-#, c-format
-msgid "The merchant %1$s offers you to purchase:"
-msgstr ""
-
-#: src/webex/pages/pay.tsx:136
-#, c-format
-msgid "The total price is %1$s (plus %2$s fees)."
-msgstr ""
-
-#: src/webex/pages/pay.tsx:141
-#, c-format
-msgid "The total price is %1$s."
-msgstr ""
-
-#: src/webex/pages/pay.tsx:163
-#, c-format
-msgid "Retry"
-msgstr ""
-
-#: src/webex/pages/pay.tsx:173
-#, c-format
-msgid "Confirm payment"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:153
-#, c-format
-msgid "Balance"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:154
-#, c-format
-msgid "History"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:155
-#, c-format
-msgid "Debug"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:175
-#, c-format
-msgid "You have no balance to show. Need some %1$s getting started?"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:238
-#, c-format
-msgid "%1$s incoming"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:250
-#, c-format
-msgid "%1$s being spent"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:281
-#, c-format
-msgid "Error: could not retrieve balance information."
-msgstr ""
-
-#: src/webex/pages/popup.tsx:390
-#, c-format
-msgid "Invalid "
-msgstr ""
-
-#: src/webex/pages/popup.tsx:396
-#, c-format
-msgid "Fees "
-msgstr ""
-
-#: src/webex/pages/popup.tsx:434
-#, c-format
-msgid "Refresh sessions has completed"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:451
-#, c-format
-msgid "Order Refused"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:465
-#, c-format
-msgid "Order redirected"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:482
-#, c-format
-msgid "Payment aborted"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:512
-#, c-format
-msgid "Payment Sent"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:536
-#, c-format
-msgid "Order accepted"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:547
-#, c-format
-msgid "Reserve balance updated"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:559
-#, c-format
-msgid "Payment refund"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:584
-#, c-format
-msgid "Withdrawn"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:596
-#, c-format
-msgid "Tip Accepted"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:606
-#, c-format
-msgid "Tip Declined"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:615
-#, c-format
-msgid "%1$s"
-msgstr ""
-
-#: src/webex/pages/popup.tsx:707
-#, c-format
-msgid "Your wallet has no events recorded."
-msgstr ""
-
-#: src/webex/pages/return-coins.tsx:124
-#, c-format
-msgid "Wire to bank account"
-msgstr ""
-
-#: src/webex/pages/return-coins.tsx:206
-#, c-format
-msgid "Confirm"
-msgstr ""
-
-#: src/webex/pages/return-coins.tsx:209
-#, c-format
-msgid "Cancel"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:73
-#, c-format
-msgid "Could not get details for withdraw operation:"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:89 src/webex/pages/withdraw.tsx:183
-#, c-format
-msgid "Chose different exchange provider"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:109
-#, c-format
-msgid ""
-"Please select an exchange. You can review the details before after your "
-"selection."
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:121
-#, c-format
-msgid "Select %1$s"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:143
-#, c-format
-msgid "Select custom exchange"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:163
-#, c-format
-msgid "You are about to withdraw %1$s from your bank account into your wallet."
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:174
-#, c-format
-msgid "Accept fees and withdraw"
-msgstr ""
-
-#: src/webex/pages/withdraw.tsx:192
-#, c-format
-msgid "Cancel withdraw operation"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:249
-#, c-format
-msgid "Withdrawal fees:"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:252
-#, c-format
-msgid "Rounding loss:"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:254
-#, c-format
-msgid "Earliest expiration (for deposit): %1$s"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:262
-#, c-format
-msgid "# Coins"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:263
-#, c-format
-msgid "Value"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:264
-#, c-format
-msgid "Withdraw Fee"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:265
-#, c-format
-msgid "Refresh Fee"
-msgstr ""
-
-#: src/webex/renderHtml.tsx:266
-#, c-format
-msgid "Deposit Fee"
-msgstr ""
diff --git a/src/index.ts b/src/index.ts
deleted file mode 100644
index 147d7b1e0..000000000
--- a/src/index.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- This file is part of TALER
- (C) 2019 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Module entry point for the wallet when used as a node module.
- */
-
-export { Wallet } from "./wallet";
-export { installAndroidWalletListener } from "./android";
diff --git a/src/operations/balance.ts b/src/operations/balance.ts
deleted file mode 100644
index 26f0aaeee..000000000
--- a/src/operations/balance.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- 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/>
- */
-
-/**
- * Imports.
- */
-import { BalancesResponse } from "../types/walletTypes";
-import { TransactionHandle } from "../util/query";
-import { InternalWalletState } from "./state";
-import { Stores, CoinStatus } from "../types/dbTypes";
-import * as Amounts from "../util/amounts";
-import { AmountJson } from "../util/amounts";
-import { Logger } from "../util/logging";
-
-const logger = new Logger("withdraw.ts");
-
-interface WalletBalance {
- available: AmountJson;
- pendingIncoming: AmountJson;
- pendingOutgoing: AmountJson;
-}
-
-/**
- * Get balance information.
- */
-export async function getBalancesInsideTransaction(
- ws: InternalWalletState,
- tx: TransactionHandle,
-): Promise<BalancesResponse> {
- const balanceStore: Record<string, WalletBalance> = {};
-
- /**
- * Add amount to a balance field, both for
- * the slicing by exchange and currency.
- */
- const initBalance = (currency: string): WalletBalance => {
- const b = balanceStore[currency];
- if (!b) {
- balanceStore[currency] = {
- available: Amounts.getZero(currency),
- pendingIncoming: Amounts.getZero(currency),
- pendingOutgoing: Amounts.getZero(currency),
- };
- }
- return balanceStore[currency];
- };
-
- // Initialize balance to zero, even if we didn't start withdrawing yet.
- await tx.iter(Stores.reserves).forEach((r) => {
- const b = initBalance(r.currency);
- if (!r.initialWithdrawalStarted) {
- b.pendingIncoming = Amounts.add(
- b.pendingIncoming,
- r.initialDenomSel.totalCoinValue,
- ).amount;
- }
- });
-
- await tx.iter(Stores.coins).forEach((c) => {
- // Only count fresh coins, as dormant coins will
- // already be in a refresh session.
- if (c.status === CoinStatus.Fresh) {
- const b = initBalance(c.currentAmount.currency);
- b.available = Amounts.add(b.available, c.currentAmount).amount;
- }
- });
-
- await tx.iter(Stores.refreshGroups).forEach((r) => {
- // Don't count finished refreshes, since the refresh already resulted
- // in coins being added to the wallet.
- if (r.timestampFinished) {
- return;
- }
- for (let i = 0; i < r.oldCoinPubs.length; i++) {
- const session = r.refreshSessionPerCoin[i];
- if (session) {
- const b = initBalance(session.amountRefreshOutput.currency);
- // We are always assuming the refresh will succeed, thus we
- // report the output as available balance.
- b.available = Amounts.add(session.amountRefreshOutput).amount;
- }
- }
- });
-
- await tx.iter(Stores.withdrawalGroups).forEach((wds) => {
- if (wds.timestampFinish) {
- return;
- }
- const b = initBalance(wds.denomsSel.totalWithdrawCost.currency);
- b.pendingIncoming = Amounts.add(
- b.pendingIncoming,
- wds.denomsSel.totalCoinValue,
- ).amount;
- });
-
- const balancesResponse: BalancesResponse = {
- balances: [],
- };
-
- Object.keys(balanceStore)
- .sort()
- .forEach((c) => {
- const v = balanceStore[c];
- balancesResponse.balances.push({
- available: Amounts.stringify(v.available),
- pendingIncoming: Amounts.stringify(v.pendingIncoming),
- pendingOutgoing: Amounts.stringify(v.pendingOutgoing),
- hasPendingTransactions: false,
- requiresUserInput: false,
- });
- });
-
- return balancesResponse;
-}
-
-/**
- * Get detailed balance information, sliced by exchange and by currency.
- */
-export async function getBalances(
- ws: InternalWalletState,
-): Promise<BalancesResponse> {
- logger.trace("starting to compute balance");
-
- const wbal = await ws.db.runWithReadTransaction(
- [
- Stores.coins,
- Stores.refreshGroups,
- Stores.reserves,
- Stores.purchases,
- Stores.withdrawalGroups,
- ],
- async (tx) => {
- return getBalancesInsideTransaction(ws, tx);
- },
- );
-
- logger.trace("finished computing wallet balance");
-
- return wbal;
-}
diff --git a/src/operations/errors.ts b/src/operations/errors.ts
deleted file mode 100644
index 198d3f8c5..000000000
--- a/src/operations/errors.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2019-2020 Taler Systems SA
-
- 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/>
- */
-
-/**
- * Classes and helpers for error handling specific to wallet operations.
- *
- * @author Florian Dold <dold@taler.net>
- */
-
-/**
- * Imports.
- */
-import { OperationErrorDetails } from "../types/walletTypes";
-import { TalerErrorCode } from "../TalerErrorCode";
-
-/**
- * This exception is there to let the caller know that an error happened,
- * but the error has already been reported by writing it to the database.
- */
-export class OperationFailedAndReportedError extends Error {
- constructor(public operationError: OperationErrorDetails) {
- super(operationError.message);
-
- // Set the prototype explicitly.
- Object.setPrototypeOf(this, OperationFailedAndReportedError.prototype);
- }
-}
-
-/**
- * This exception is thrown when an error occured and the caller is
- * responsible for recording the failure in the database.
- */
-export class OperationFailedError extends Error {
- static fromCode(
- ec: TalerErrorCode,
- message: string,
- details: Record<string, unknown>,
- ): OperationFailedError {
- return new OperationFailedError(makeErrorDetails(ec, message, details));
- }
-
- constructor(public operationError: OperationErrorDetails) {
- super(operationError.message);
-
- // Set the prototype explicitly.
- Object.setPrototypeOf(this, OperationFailedError.prototype);
- }
-}
-
-export function makeErrorDetails(
- ec: TalerErrorCode,
- message: string,
- details: Record<string, unknown>,
-): OperationErrorDetails {
- return {
- talerErrorCode: ec,
- talerErrorHint: `Error: ${TalerErrorCode[ec]}`,
- details: details,
- message,
- };
-}
-
-/**
- * Run an operation and call the onOpError callback
- * when there was an exception or operation error that must be reported.
- * The cause will be re-thrown to the caller.
- */
-export async function guardOperationException<T>(
- op: () => Promise<T>,
- onOpError: (e: OperationErrorDetails) => Promise<void>,
-): Promise<T> {
- try {
- return await op();
- } catch (e) {
- if (e instanceof OperationFailedAndReportedError) {
- throw e;
- }
- if (e instanceof OperationFailedError) {
- await onOpError(e.operationError);
- throw new OperationFailedAndReportedError(e.operationError);
- }
- if (e instanceof Error) {
- const opErr = makeErrorDetails(
- TalerErrorCode.WALLET_UNEXPECTED_EXCEPTION,
- `unexpected exception (message: ${e.message})`,
- {},
- );
- await onOpError(opErr);
- throw new OperationFailedAndReportedError(opErr);
- }
- // Something was thrown that is not even an exception!
- // Try to stringify it.
- let excString: string;
- try {
- excString = e.toString();
- } catch (e) {
- // Something went horribly wrong.
- excString = "can't stringify exception";
- }
- const opErr = makeErrorDetails(
- TalerErrorCode.WALLET_UNEXPECTED_EXCEPTION,
- `unexpected exception (not an exception, ${excString})`,
- {},
- );
- await onOpError(opErr);
- throw new OperationFailedAndReportedError(opErr);
- }
-}
diff --git a/src/operations/exchanges.ts b/src/operations/exchanges.ts
deleted file mode 100644
index 6b995b5e9..000000000
--- a/src/operations/exchanges.ts
+++ /dev/null
@@ -1,554 +0,0 @@
-/*
- 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 { InternalWalletState } from "./state";
-import {
- Denomination,
- codecForExchangeKeysJson,
- codecForExchangeWireJson,
-} from "../types/talerTypes";
-import { OperationErrorDetails } from "../types/walletTypes";
-import {
- ExchangeRecord,
- ExchangeUpdateStatus,
- Stores,
- DenominationRecord,
- DenominationStatus,
- WireFee,
- ExchangeUpdateReason,
- ExchangeUpdatedEventRecord,
-} from "../types/dbTypes";
-import { canonicalizeBaseUrl } from "../util/helpers";
-import * as Amounts from "../util/amounts";
-import { parsePaytoUri } from "../util/payto";
-import {
- OperationFailedAndReportedError,
- guardOperationException,
- makeErrorDetails,
-} from "./errors";
-import {
- WALLET_CACHE_BREAKER_CLIENT_VERSION,
- WALLET_EXCHANGE_PROTOCOL_VERSION,
-} from "./versions";
-import { getTimestampNow } from "../util/time";
-import { compare } from "../util/libtoolVersion";
-import { createRecoupGroup, processRecoupGroup } from "./recoup";
-import { TalerErrorCode } from "../TalerErrorCode";
-import {
- readSuccessResponseJsonOrThrow,
- readSuccessResponseTextOrThrow,
-} from "../util/http";
-import { Logger } from "../util/logging";
-
-const logger = new Logger("exchanges.ts");
-
-async function denominationRecordFromKeys(
- ws: InternalWalletState,
- exchangeBaseUrl: string,
- denomIn: Denomination,
-): Promise<DenominationRecord> {
- const denomPubHash = await ws.cryptoApi.hashEncoded(denomIn.denom_pub);
- const d: DenominationRecord = {
- denomPub: denomIn.denom_pub,
- denomPubHash,
- exchangeBaseUrl,
- feeDeposit: Amounts.parseOrThrow(denomIn.fee_deposit),
- feeRefresh: Amounts.parseOrThrow(denomIn.fee_refresh),
- feeRefund: Amounts.parseOrThrow(denomIn.fee_refund),
- feeWithdraw: Amounts.parseOrThrow(denomIn.fee_withdraw),
- isOffered: true,
- isRevoked: false,
- masterSig: denomIn.master_sig,
- stampExpireDeposit: denomIn.stamp_expire_deposit,
- stampExpireLegal: denomIn.stamp_expire_legal,
- stampExpireWithdraw: denomIn.stamp_expire_withdraw,
- stampStart: denomIn.stamp_start,
- status: DenominationStatus.Unverified,
- value: Amounts.parseOrThrow(denomIn.value),
- };
- return d;
-}
-
-async function setExchangeError(
- ws: InternalWalletState,
- baseUrl: string,
- err: OperationErrorDetails,
-): Promise<void> {
- console.log(`last error for exchange ${baseUrl}:`, err);
- const mut = (exchange: ExchangeRecord): ExchangeRecord => {
- exchange.lastError = err;
- return exchange;
- };
- await ws.db.mutate(Stores.exchanges, baseUrl, mut);
-}
-
-/**
- * Fetch the exchange's /keys and update our database accordingly.
- *
- * Exceptions thrown in this method must be caught and reported
- * in the pending operations.
- */
-async function updateExchangeWithKeys(
- ws: InternalWalletState,
- baseUrl: string,
-): Promise<void> {
- const existingExchangeRecord = await ws.db.get(Stores.exchanges, baseUrl);
-
- if (existingExchangeRecord?.updateStatus != ExchangeUpdateStatus.FetchKeys) {
- return;
- }
-
- const keysUrl = new URL("keys", baseUrl);
- keysUrl.searchParams.set("cacheBreaker", WALLET_CACHE_BREAKER_CLIENT_VERSION);
-
- const resp = await ws.http.get(keysUrl.href);
- const exchangeKeysJson = await readSuccessResponseJsonOrThrow(
- resp,
- codecForExchangeKeysJson(),
- );
-
- if (exchangeKeysJson.denoms.length === 0) {
- const opErr = makeErrorDetails(
- TalerErrorCode.WALLET_EXCHANGE_DENOMINATIONS_INSUFFICIENT,
- "exchange doesn't offer any denominations",
- {
- exchangeBaseUrl: baseUrl,
- },
- );
- await setExchangeError(ws, baseUrl, opErr);
- throw new OperationFailedAndReportedError(opErr);
- }
-
- const protocolVersion = exchangeKeysJson.version;
-
- const versionRes = compare(WALLET_EXCHANGE_PROTOCOL_VERSION, protocolVersion);
- if (versionRes?.compatible != true) {
- const opErr = makeErrorDetails(
- TalerErrorCode.WALLET_EXCHANGE_PROTOCOL_VERSION_INCOMPATIBLE,
- "exchange protocol version not compatible with wallet",
- {
- exchangeProtocolVersion: protocolVersion,
- walletProtocolVersion: WALLET_EXCHANGE_PROTOCOL_VERSION,
- },
- );
- await setExchangeError(ws, baseUrl, opErr);
- throw new OperationFailedAndReportedError(opErr);
- }
-
- const currency = Amounts.parseOrThrow(exchangeKeysJson.denoms[0].value)
- .currency;
-
- const newDenominations = await Promise.all(
- exchangeKeysJson.denoms.map((d) =>
- denominationRecordFromKeys(ws, baseUrl, d),
- ),
- );
-
- const lastUpdateTimestamp = getTimestampNow();
-
- const recoupGroupId: string | undefined = undefined;
-
- await ws.db.runWithWriteTransaction(
- [Stores.exchanges, Stores.denominations, Stores.recoupGroups, Stores.coins],
- async (tx) => {
- const r = await tx.get(Stores.exchanges, baseUrl);
- if (!r) {
- console.warn(`exchange ${baseUrl} no longer present`);
- return;
- }
- if (r.details) {
- // FIXME: We need to do some consistency checks!
- }
- // FIXME: validate signing keys and merge with old set
- r.details = {
- auditors: exchangeKeysJson.auditors,
- currency: currency,
- lastUpdateTime: lastUpdateTimestamp,
- masterPublicKey: exchangeKeysJson.master_public_key,
- protocolVersion: protocolVersion,
- signingKeys: exchangeKeysJson.signkeys,
- };
- r.updateStatus = ExchangeUpdateStatus.FetchWire;
- r.lastError = undefined;
- await tx.put(Stores.exchanges, r);
-
- for (const newDenom of newDenominations) {
- const oldDenom = await tx.get(Stores.denominations, [
- baseUrl,
- newDenom.denomPub,
- ]);
- if (oldDenom) {
- // FIXME: Do consistency check
- } else {
- await tx.put(Stores.denominations, newDenom);
- }
- }
-
- // Handle recoup
- const recoupDenomList = exchangeKeysJson.recoup ?? [];
- const newlyRevokedCoinPubs: string[] = [];
- logger.trace("recoup list from exchange", recoupDenomList);
- for (const recoupInfo of recoupDenomList) {
- const oldDenom = await tx.getIndexed(
- Stores.denominations.denomPubHashIndex,
- recoupInfo.h_denom_pub,
- );
- if (!oldDenom) {
- // We never even knew about the revoked denomination, all good.
- continue;
- }
- if (oldDenom.isRevoked) {
- // We already marked the denomination as revoked,
- // this implies we revoked all coins
- console.log("denom already revoked");
- continue;
- }
- console.log("revoking denom", recoupInfo.h_denom_pub);
- oldDenom.isRevoked = true;
- await tx.put(Stores.denominations, oldDenom);
- const affectedCoins = await tx
- .iterIndexed(Stores.coins.denomPubHashIndex, recoupInfo.h_denom_pub)
- .toArray();
- for (const ac of affectedCoins) {
- newlyRevokedCoinPubs.push(ac.coinPub);
- }
- }
- if (newlyRevokedCoinPubs.length != 0) {
- console.log("recouping coins", newlyRevokedCoinPubs);
- await createRecoupGroup(ws, tx, newlyRevokedCoinPubs);
- }
- },
- );
-
- if (recoupGroupId) {
- // Asynchronously start recoup. This doesn't need to finish
- // for the exchange update to be considered finished.
- processRecoupGroup(ws, recoupGroupId).catch((e) => {
- console.log("error while recouping coins:", e);
- });
- }
-}
-
-async function updateExchangeFinalize(
- ws: InternalWalletState,
- exchangeBaseUrl: string,
-): Promise<void> {
- const exchange = await ws.db.get(Stores.exchanges, exchangeBaseUrl);
- if (!exchange) {
- return;
- }
- if (exchange.updateStatus != ExchangeUpdateStatus.FinalizeUpdate) {
- return;
- }
- await ws.db.runWithWriteTransaction(
- [Stores.exchanges, Stores.exchangeUpdatedEvents],
- async (tx) => {
- const r = await tx.get(Stores.exchanges, exchangeBaseUrl);
- if (!r) {
- return;
- }
- if (r.updateStatus != ExchangeUpdateStatus.FinalizeUpdate) {
- return;
- }
- r.addComplete = true;
- r.updateStatus = ExchangeUpdateStatus.Finished;
- await tx.put(Stores.exchanges, r);
- const updateEvent: ExchangeUpdatedEventRecord = {
- exchangeBaseUrl: exchange.baseUrl,
- timestamp: getTimestampNow(),
- };
- await tx.put(Stores.exchangeUpdatedEvents, updateEvent);
- },
- );
-}
-
-async function updateExchangeWithTermsOfService(
- ws: InternalWalletState,
- exchangeBaseUrl: string,
-): Promise<void> {
- const exchange = await ws.db.get(Stores.exchanges, exchangeBaseUrl);
- if (!exchange) {
- return;
- }
- if (exchange.updateStatus != ExchangeUpdateStatus.FetchTerms) {
- return;
- }
- const reqUrl = new URL("terms", exchangeBaseUrl);
- reqUrl.searchParams.set("cacheBreaker", WALLET_CACHE_BREAKER_CLIENT_VERSION);
- const headers = {
- Accept: "text/plain",
- };
-
- const resp = await ws.http.get(reqUrl.href, { headers });
- const tosText = await readSuccessResponseTextOrThrow(resp);
- const tosEtag = resp.headers.get("etag") || undefined;
-
- await ws.db.runWithWriteTransaction([Stores.exchanges], async (tx) => {
- const r = await tx.get(Stores.exchanges, exchangeBaseUrl);
- if (!r) {
- return;
- }
- if (r.updateStatus != ExchangeUpdateStatus.FetchTerms) {
- return;
- }
- r.termsOfServiceText = tosText;
- r.termsOfServiceLastEtag = tosEtag;
- r.updateStatus = ExchangeUpdateStatus.FinalizeUpdate;
- await tx.put(Stores.exchanges, r);
- });
-}
-
-export async function acceptExchangeTermsOfService(
- ws: InternalWalletState,
- exchangeBaseUrl: string,
- etag: string | undefined,
-): Promise<void> {
- await ws.db.runWithWriteTransaction([Stores.exchanges], async (tx) => {
- const r = await tx.get(Stores.exchanges, exchangeBaseUrl);
- if (!r) {
- return;
- }
- r.termsOfServiceAcceptedEtag = etag;
- r.termsOfServiceAcceptedTimestamp = getTimestampNow();
- await tx.put(Stores.exchanges, r);
- });
-}
-
-/**
- * Fetch wire information for an exchange and store it in the database.
- *
- * @param exchangeBaseUrl Exchange base URL, assumed to be already normalized.
- */
-async function updateExchangeWithWireInfo(
- ws: InternalWalletState,
- exchangeBaseUrl: string,
-): Promise<void> {
- const exchange = await ws.db.get(Stores.exchanges, exchangeBaseUrl);
- if (!exchange) {
- return;
- }
- if (exchange.updateStatus != ExchangeUpdateStatus.FetchWire) {
- return;
- }
- const details = exchange.details;
- if (!details) {
- throw Error("invalid exchange state");
- }
- const reqUrl = new URL("wire", exchangeBaseUrl);
- reqUrl.searchParams.set("cacheBreaker", WALLET_CACHE_BREAKER_CLIENT_VERSION);
-
- const resp = await ws.http.get(reqUrl.href);
- const wireInfo = await readSuccessResponseJsonOrThrow(
- resp,
- codecForExchangeWireJson(),
- );
-
- for (const a of wireInfo.accounts) {
- logger.trace("validating exchange acct");
- const isValid = await ws.cryptoApi.isValidWireAccount(
- a.payto_uri,
- a.master_sig,
- details.masterPublicKey,
- );
- if (!isValid) {
- throw Error("exchange acct signature invalid");
- }
- }
- const feesForType: { [wireMethod: string]: WireFee[] } = {};
- for (const wireMethod of Object.keys(wireInfo.fees)) {
- const feeList: WireFee[] = [];
- for (const x of wireInfo.fees[wireMethod]) {
- const startStamp = x.start_date;
- const endStamp = x.end_date;
- const fee: WireFee = {
- closingFee: Amounts.parseOrThrow(x.closing_fee),
- endStamp,
- sig: x.sig,
- startStamp,
- wireFee: Amounts.parseOrThrow(x.wire_fee),
- };
- const isValid = await ws.cryptoApi.isValidWireFee(
- wireMethod,
- fee,
- details.masterPublicKey,
- );
- if (!isValid) {
- throw Error("exchange wire fee signature invalid");
- }
- feeList.push(fee);
- }
- feesForType[wireMethod] = feeList;
- }
-
- await ws.db.runWithWriteTransaction([Stores.exchanges], async (tx) => {
- const r = await tx.get(Stores.exchanges, exchangeBaseUrl);
- if (!r) {
- return;
- }
- if (r.updateStatus != ExchangeUpdateStatus.FetchWire) {
- return;
- }
- r.wireInfo = {
- accounts: wireInfo.accounts,
- feesForType: feesForType,
- };
- r.updateStatus = ExchangeUpdateStatus.FetchTerms;
- r.lastError = undefined;
- await tx.put(Stores.exchanges, r);
- });
-}
-
-export async function updateExchangeFromUrl(
- ws: InternalWalletState,
- baseUrl: string,
- forceNow = false,
-): Promise<ExchangeRecord> {
- const onOpErr = (e: OperationErrorDetails): Promise<void> =>
- setExchangeError(ws, baseUrl, e);
- return await guardOperationException(
- () => updateExchangeFromUrlImpl(ws, baseUrl, forceNow),
- onOpErr,
- );
-}
-
-/**
- * Update or add exchange DB entry by fetching the /keys and /wire information.
- * Optionally link the reserve entry to the new or existing
- * exchange entry in then DB.
- */
-async function updateExchangeFromUrlImpl(
- ws: InternalWalletState,
- baseUrl: string,
- forceNow = false,
-): Promise<ExchangeRecord> {
- const now = getTimestampNow();
- baseUrl = canonicalizeBaseUrl(baseUrl);
-
- const r = await ws.db.get(Stores.exchanges, baseUrl);
- if (!r) {
- const newExchangeRecord: ExchangeRecord = {
- builtIn: false,
- addComplete: false,
- permanent: true,
- baseUrl: baseUrl,
- details: undefined,
- wireInfo: undefined,
- updateStatus: ExchangeUpdateStatus.FetchKeys,
- updateStarted: now,
- updateReason: ExchangeUpdateReason.Initial,
- timestampAdded: getTimestampNow(),
- termsOfServiceAcceptedEtag: undefined,
- termsOfServiceAcceptedTimestamp: undefined,
- termsOfServiceLastEtag: undefined,
- termsOfServiceText: undefined,
- updateDiff: undefined,
- };
- await ws.db.put(Stores.exchanges, newExchangeRecord);
- } else {
- await ws.db.runWithWriteTransaction([Stores.exchanges], async (t) => {
- const rec = await t.get(Stores.exchanges, baseUrl);
- if (!rec) {
- return;
- }
- if (rec.updateStatus != ExchangeUpdateStatus.FetchKeys && !forceNow) {
- return;
- }
- if (rec.updateStatus != ExchangeUpdateStatus.FetchKeys && forceNow) {
- rec.updateReason = ExchangeUpdateReason.Forced;
- }
- rec.updateStarted = now;
- rec.updateStatus = ExchangeUpdateStatus.FetchKeys;
- rec.lastError = undefined;
- t.put(Stores.exchanges, rec);
- });
- }
-
- await updateExchangeWithKeys(ws, baseUrl);
- await updateExchangeWithWireInfo(ws, baseUrl);
- await updateExchangeWithTermsOfService(ws, baseUrl);
- await updateExchangeFinalize(ws, baseUrl);
-
- const updatedExchange = await ws.db.get(Stores.exchanges, baseUrl);
-
- if (!updatedExchange) {
- // This should practically never happen
- throw Error("exchange not found");
- }
- return updatedExchange;
-}
-
-/**
- * Check if and how an exchange is trusted and/or audited.
- */
-export async function getExchangeTrust(
- ws: InternalWalletState,
- exchangeInfo: ExchangeRecord,
-): Promise<{ isTrusted: boolean; isAudited: boolean }> {
- let isTrusted = false;
- let isAudited = false;
- const exchangeDetails = exchangeInfo.details;
- if (!exchangeDetails) {
- throw Error(`exchange ${exchangeInfo.baseUrl} details not available`);
- }
- const currencyRecord = await ws.db.get(
- Stores.currencies,
- exchangeDetails.currency,
- );
- if (currencyRecord) {
- for (const trustedExchange of currencyRecord.exchanges) {
- if (trustedExchange.exchangePub === exchangeDetails.masterPublicKey) {
- isTrusted = true;
- break;
- }
- }
- for (const trustedAuditor of currencyRecord.auditors) {
- for (const exchangeAuditor of exchangeDetails.auditors) {
- if (trustedAuditor.auditorPub === exchangeAuditor.auditor_pub) {
- isAudited = true;
- break;
- }
- }
- }
- }
- return { isTrusted, isAudited };
-}
-
-export async function getExchangePaytoUri(
- ws: InternalWalletState,
- exchangeBaseUrl: string,
- supportedTargetTypes: string[],
-): Promise<string> {
- // We do the update here, since the exchange might not even exist
- // yet in our database.
- const exchangeRecord = await updateExchangeFromUrl(ws, exchangeBaseUrl);
- if (!exchangeRecord) {
- throw Error(`Exchange '${exchangeBaseUrl}' not found.`);
- }
- const exchangeWireInfo = exchangeRecord.wireInfo;
- if (!exchangeWireInfo) {
- throw Error(`Exchange wire info for '${exchangeBaseUrl}' not found.`);
- }
- for (const account of exchangeWireInfo.accounts) {
- const res = parsePaytoUri(account.payto_uri);
- if (!res) {
- continue;
- }
- if (supportedTargetTypes.includes(res.targetType)) {
- return account.payto_uri;
- }
- }
- throw Error("no matching exchange account found");
-}
diff --git a/src/operations/pay.ts b/src/operations/pay.ts
deleted file mode 100644
index 9cbda5ba5..000000000
--- a/src/operations/pay.ts
+++ /dev/null
@@ -1,1147 +0,0 @@
-/*
- 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/>
- */
-
-/**
- * Implementation of the payment operation, including downloading and
- * claiming of proposals.
- *
- * @author Florian Dold
- */
-
-/**
- * Imports.
- */
-import { encodeCrock, getRandomBytes } from "../crypto/talerCrypto";
-import {
- CoinStatus,
- initRetryInfo,
- ProposalRecord,
- ProposalStatus,
- PurchaseRecord,
- Stores,
- updateRetryInfoTimeout,
- PayEventRecord,
- WalletContractData,
-} from "../types/dbTypes";
-import { NotificationType } from "../types/notifications";
-import {
- codecForProposal,
- codecForContractTerms,
- CoinDepositPermission,
- codecForMerchantPayResponse,
-} from "../types/talerTypes";
-import {
- ConfirmPayResult,
- OperationErrorDetails,
- PreparePayResult,
- RefreshReason,
- PreparePayResultType,
-} from "../types/walletTypes";
-import * as Amounts from "../util/amounts";
-import { AmountJson } from "../util/amounts";
-import { Logger } from "../util/logging";
-import { parsePayUri } from "../util/taleruri";
-import { guardOperationException, OperationFailedError } from "./errors";
-import { createRefreshGroup, getTotalRefreshCost } from "./refresh";
-import { InternalWalletState } from "./state";
-import { getTimestampNow, timestampAddDuration } from "../util/time";
-import { strcmp, canonicalJson } from "../util/helpers";
-import { readSuccessResponseJsonOrThrow } from "../util/http";
-import { TalerErrorCode } from "../TalerErrorCode";
-
-/**
- * Logger.
- */
-const logger = new Logger("pay.ts");
-
-/**
- * Result of selecting coins, contains the exchange, and selected
- * coins with their denomination.
- */
-export interface PayCoinSelection {
- /**
- * Amount requested by the merchant.
- */
- paymentAmount: AmountJson;
-
- /**
- * Public keys of the coins that were selected.
- */
- coinPubs: string[];
-
- /**
- * Amount that each coin contributes.
- */
- coinContributions: AmountJson[];
-
- /**
- * How much of the wire fees is the customer paying?
- */
- customerWireFees: AmountJson;
-
- /**
- * How much of the deposit fees is the customer paying?
- */
- customerDepositFees: AmountJson;
-}
-
-/**
- * Structure to describe a coin that is available to be
- * used in a payment.
- */
-export interface AvailableCoinInfo {
- /**
- * Public key of the coin.
- */
- coinPub: string;
-
- /**
- * Coin's denomination public key.
- */
- denomPub: string;
-
- /**
- * Amount still remaining (typically the full amount,
- * as coins are always refreshed after use.)
- */
- availableAmount: AmountJson;
-
- /**
- * Deposit fee for the coin.
- */
- feeDeposit: AmountJson;
-}
-
-export interface PayCostInfo {
- totalCost: AmountJson;
-}
-
-/**
- * Compute the total cost of a payment to the customer.
- *
- * This includes the amount taken by the merchant, fees (wire/deposit) contributed
- * by the customer, refreshing fees, fees for withdraw-after-refresh and "trimmings"
- * of coins that are too small to spend.
- */
-export async function getTotalPaymentCost(
- ws: InternalWalletState,
- pcs: PayCoinSelection,
-): Promise<PayCostInfo> {
- const costs = [];
- for (let i = 0; i < pcs.coinPubs.length; i++) {
- const coin = await ws.db.get(Stores.coins, pcs.coinPubs[i]);
- if (!coin) {
- throw Error("can't calculate payment cost, coin not found");
- }
- const denom = await ws.db.get(Stores.denominations, [
- coin.exchangeBaseUrl,
- coin.denomPub,
- ]);
- if (!denom) {
- throw Error(
- "can't calculate payment cost, denomination for coin not found",
- );
- }
- const allDenoms = await ws.db
- .iterIndex(
- Stores.denominations.exchangeBaseUrlIndex,
- coin.exchangeBaseUrl,
- )
- .toArray();
- const amountLeft = Amounts.sub(denom.value, pcs.coinContributions[i])
- .amount;
- const refreshCost = getTotalRefreshCost(allDenoms, denom, amountLeft);
- costs.push(pcs.coinContributions[i]);
- costs.push(refreshCost);
- }
- return {
- totalCost: Amounts.sum(costs).amount,
- };
-}
-
-/**
- * Given a list of available coins, select coins to spend under the merchant's
- * constraints.
- *
- * This function is only exported for the sake of unit tests.
- */
-export function selectPayCoins(
- acis: AvailableCoinInfo[],
- contractTermsAmount: AmountJson,
- customerWireFees: AmountJson,
- depositFeeLimit: AmountJson,
-): PayCoinSelection | undefined {
- if (acis.length === 0) {
- return undefined;
- }
- const coinPubs: string[] = [];
- const coinContributions: AmountJson[] = [];
- // Sort by available amount (descending), deposit fee (ascending) and
- // denomPub (ascending) if deposit fee is the same
- // (to guarantee deterministic results)
- acis.sort(
- (o1, o2) =>
- -Amounts.cmp(o1.availableAmount, o2.availableAmount) ||
- Amounts.cmp(o1.feeDeposit, o2.feeDeposit) ||
- strcmp(o1.denomPub, o2.denomPub),
- );
- const paymentAmount = Amounts.add(contractTermsAmount, customerWireFees)
- .amount;
- const currency = paymentAmount.currency;
- let amountPayRemaining = paymentAmount;
- let amountDepositFeeLimitRemaining = depositFeeLimit;
- const customerDepositFees = Amounts.getZero(currency);
- for (const aci of acis) {
- // Don't use this coin if depositing it is more expensive than
- // the amount it would give the merchant.
- if (Amounts.cmp(aci.feeDeposit, aci.availableAmount) >= 0) {
- continue;
- }
- if (amountPayRemaining.value === 0 && amountPayRemaining.fraction === 0) {
- // We have spent enough!
- break;
- }
-
- // How much does the user spend on deposit fees for this coin?
- const depositFeeSpend = Amounts.sub(
- aci.feeDeposit,
- amountDepositFeeLimitRemaining,
- ).amount;
-
- if (Amounts.isZero(depositFeeSpend)) {
- // Fees are still covered by the merchant.
- amountDepositFeeLimitRemaining = Amounts.sub(
- amountDepositFeeLimitRemaining,
- aci.feeDeposit,
- ).amount;
- } else {
- amountDepositFeeLimitRemaining = Amounts.getZero(currency);
- }
-
- let coinSpend: AmountJson;
- const amountActualAvailable = Amounts.sub(
- aci.availableAmount,
- depositFeeSpend,
- ).amount;
-
- if (Amounts.cmp(amountActualAvailable, amountPayRemaining) > 0) {
- // Partial spending, as the coin is worth more than the remaining
- // amount to pay.
- coinSpend = Amounts.add(amountPayRemaining, depositFeeSpend).amount;
- // Make sure we contribute at least the deposit fee, otherwise
- // contributing this coin would cause a loss for the merchant.
- if (Amounts.cmp(coinSpend, aci.feeDeposit) < 0) {
- coinSpend = aci.feeDeposit;
- }
- amountPayRemaining = Amounts.getZero(currency);
- } else {
- // Spend the full remaining amount on the coin
- coinSpend = aci.availableAmount;
- amountPayRemaining = Amounts.add(amountPayRemaining, depositFeeSpend)
- .amount;
- amountPayRemaining = Amounts.sub(amountPayRemaining, aci.availableAmount)
- .amount;
- }
-
- coinPubs.push(aci.coinPub);
- coinContributions.push(coinSpend);
- }
- if (Amounts.isZero(amountPayRemaining)) {
- return {
- paymentAmount: contractTermsAmount,
- coinContributions,
- coinPubs,
- customerDepositFees,
- customerWireFees,
- };
- }
- return undefined;
-}
-
-/**
- * Select coins from the wallet's database that can be used
- * to pay for the given contract.
- *
- * If payment is impossible, undefined is returned.
- */
-async function getCoinsForPayment(
- ws: InternalWalletState,
- contractData: WalletContractData,
-): Promise<PayCoinSelection | undefined> {
- const remainingAmount = contractData.amount;
-
- const exchanges = await ws.db.iter(Stores.exchanges).toArray();
-
- for (const exchange of exchanges) {
- let isOkay = false;
- const exchangeDetails = exchange.details;
- if (!exchangeDetails) {
- continue;
- }
- const exchangeFees = exchange.wireInfo;
- if (!exchangeFees) {
- continue;
- }
-
- // is the exchange explicitly allowed?
- for (const allowedExchange of contractData.allowedExchanges) {
- if (allowedExchange.exchangePub === exchangeDetails.masterPublicKey) {
- isOkay = true;
- break;
- }
- }
-
- // is the exchange allowed because of one of its auditors?
- if (!isOkay) {
- for (const allowedAuditor of contractData.allowedAuditors) {
- for (const auditor of exchangeDetails.auditors) {
- if (auditor.auditor_pub === allowedAuditor.auditorPub) {
- isOkay = true;
- break;
- }
- }
- if (isOkay) {
- break;
- }
- }
- }
-
- if (!isOkay) {
- continue;
- }
-
- const coins = await ws.db
- .iterIndex(Stores.coins.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 ws.db.get(Stores.denominations, [
- exchange.baseUrl,
- coins[0].denomPub,
- ]);
- if (!firstDenom) {
- throw Error("db inconsistent");
- }
- const currency = firstDenom.value.currency;
- const acis: AvailableCoinInfo[] = [];
- for (const coin of coins) {
- const denom = await ws.db.get(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;
- }
- acis.push({
- availableAmount: coin.currentAmount,
- coinPub: coin.coinPub,
- denomPub: coin.denomPub,
- feeDeposit: denom.feeDeposit,
- });
- }
-
- let wireFee: AmountJson | undefined;
- for (const fee of exchangeFees.feesForType[contractData.wireMethod] || []) {
- if (
- fee.startStamp <= contractData.timestamp &&
- fee.endStamp >= contractData.timestamp
- ) {
- wireFee = fee.wireFee;
- break;
- }
- }
-
- let customerWireFee: AmountJson;
-
- if (wireFee) {
- const amortizedWireFee = Amounts.divide(
- wireFee,
- contractData.wireFeeAmortization,
- );
- if (Amounts.cmp(contractData.maxWireFee, amortizedWireFee) < 0) {
- customerWireFee = amortizedWireFee;
- } else {
- customerWireFee = Amounts.getZero(currency);
- }
- } else {
- customerWireFee = Amounts.getZero(currency);
- }
-
- // Try if paying using this exchange works
- const res = selectPayCoins(
- acis,
- remainingAmount,
- customerWireFee,
- contractData.maxDepositFee,
- );
- if (res) {
- return res;
- }
- }
- 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,
- coinSelection: PayCoinSelection,
- coinDepositPermissions: CoinDepositPermission[],
- sessionIdOverride: string | undefined,
-): Promise<PurchaseRecord> {
- const d = proposal.download;
- if (!d) {
- throw Error("proposal is in invalid state");
- }
- let sessionId;
- if (sessionIdOverride) {
- sessionId = sessionIdOverride;
- } else {
- sessionId = proposal.downloadSessionId;
- }
- logger.trace(`recording payment with session ID ${sessionId}`);
- const payCostInfo = await getTotalPaymentCost(ws, coinSelection);
- const t: PurchaseRecord = {
- abortDone: false,
- abortRequested: false,
- contractTermsRaw: d.contractTermsRaw,
- contractData: d.contractData,
- lastSessionId: sessionId,
- payCoinSelection: coinSelection,
- payCostInfo,
- coinDepositPermissions,
- timestampAccept: getTimestampNow(),
- timestampLastRefundStatus: undefined,
- proposalId: proposal.proposalId,
- lastPayError: undefined,
- lastRefundStatusError: undefined,
- payRetryInfo: initRetryInfo(),
- refundStatusRetryInfo: initRetryInfo(),
- refundStatusRequested: false,
- timestampFirstSuccessfulPay: undefined,
- autoRefundDeadline: undefined,
- paymentSubmitPending: true,
- refunds: {},
- };
-
- await ws.db.runWithWriteTransaction(
- [Stores.coins, Stores.purchases, Stores.proposals, Stores.refreshGroups],
- async (tx) => {
- const p = await tx.get(Stores.proposals, proposal.proposalId);
- if (p) {
- p.proposalStatus = ProposalStatus.ACCEPTED;
- p.lastError = undefined;
- p.retryInfo = initRetryInfo(false);
- await tx.put(Stores.proposals, p);
- }
- await tx.put(Stores.purchases, t);
- for (let i = 0; i < coinSelection.coinPubs.length; i++) {
- const coin = await tx.get(Stores.coins, coinSelection.coinPubs[i]);
- if (!coin) {
- throw Error("coin allocated for payment doesn't exist anymore");
- }
- coin.status = CoinStatus.Dormant;
- const remaining = Amounts.sub(
- coin.currentAmount,
- coinSelection.coinContributions[i],
- );
- if (remaining.saturated) {
- throw Error("not enough remaining balance on coin for payment");
- }
- coin.currentAmount = remaining.amount;
- await tx.put(Stores.coins, coin);
- }
- const refreshCoinPubs = coinSelection.coinPubs.map((x) => ({
- coinPub: x,
- }));
- await createRefreshGroup(ws, tx, refreshCoinPubs, RefreshReason.Pay);
- },
- );
-
- ws.notify({
- type: NotificationType.ProposalAccepted,
- proposalId: proposal.proposalId,
- });
- return t;
-}
-
-function getNextUrl(contractData: WalletContractData): string {
- const f = contractData.fulfillmentUrl;
- if (f.startsWith("http://") || f.startsWith("https://")) {
- const fu = new URL(contractData.fulfillmentUrl);
- fu.searchParams.set("order_id", contractData.orderId);
- return fu.href;
- } else {
- return f;
- }
-}
-
-async function incrementProposalRetry(
- ws: InternalWalletState,
- proposalId: string,
- err: OperationErrorDetails | undefined,
-): Promise<void> {
- await ws.db.runWithWriteTransaction([Stores.proposals], async (tx) => {
- const pr = await tx.get(Stores.proposals, proposalId);
- if (!pr) {
- return;
- }
- if (!pr.retryInfo) {
- return;
- }
- pr.retryInfo.retryCounter++;
- updateRetryInfoTimeout(pr.retryInfo);
- pr.lastError = err;
- await tx.put(Stores.proposals, pr);
- });
- if (err) {
- ws.notify({ type: NotificationType.ProposalOperationError, error: err });
- }
-}
-
-async function incrementPurchasePayRetry(
- ws: InternalWalletState,
- proposalId: string,
- err: OperationErrorDetails | undefined,
-): Promise<void> {
- console.log("incrementing purchase pay retry with error", err);
- await ws.db.runWithWriteTransaction([Stores.purchases], async (tx) => {
- const pr = await tx.get(Stores.purchases, proposalId);
- if (!pr) {
- return;
- }
- if (!pr.payRetryInfo) {
- return;
- }
- pr.payRetryInfo.retryCounter++;
- updateRetryInfoTimeout(pr.payRetryInfo);
- pr.lastPayError = err;
- await tx.put(Stores.purchases, pr);
- });
- if (err) {
- ws.notify({ type: NotificationType.PayOperationError, error: err });
- }
-}
-
-export async function processDownloadProposal(
- ws: InternalWalletState,
- proposalId: string,
- forceNow = false,
-): Promise<void> {
- const onOpErr = (err: OperationErrorDetails): Promise<void> =>
- incrementProposalRetry(ws, proposalId, err);
- await guardOperationException(
- () => processDownloadProposalImpl(ws, proposalId, forceNow),
- onOpErr,
- );
-}
-
-async function resetDownloadProposalRetry(
- ws: InternalWalletState,
- proposalId: string,
-): Promise<void> {
- await ws.db.mutate(Stores.proposals, proposalId, (x) => {
- if (x.retryInfo.active) {
- x.retryInfo = initRetryInfo();
- }
- return x;
- });
-}
-
-async function processDownloadProposalImpl(
- ws: InternalWalletState,
- proposalId: string,
- forceNow: boolean,
-): Promise<void> {
- if (forceNow) {
- await resetDownloadProposalRetry(ws, proposalId);
- }
- const proposal = await ws.db.get(Stores.proposals, proposalId);
- if (!proposal) {
- return;
- }
- if (proposal.proposalStatus != ProposalStatus.DOWNLOADING) {
- return;
- }
-
- const orderClaimUrl = new URL(
- `orders/${proposal.orderId}/claim`,
- proposal.merchantBaseUrl,
- ).href;
- logger.trace("downloading contract from '" + orderClaimUrl + "'");
-
- const requestBody: {
- nonce: string,
- token?: string;
- } = {
- nonce: proposal.noncePub,
- };
- if (proposal.claimToken) {
- requestBody.token = proposal.claimToken;
- }
-
- const resp = await ws.http.postJson(orderClaimUrl, requestBody);
- const proposalResp = await readSuccessResponseJsonOrThrow(
- resp,
- codecForProposal(),
- );
-
- // The proposalResp contains the contract terms as raw JSON,
- // as the coded to parse them doesn't necessarily round-trip.
- // We need this raw JSON to compute the contract terms hash.
-
- const contractTermsHash = await ws.cryptoApi.hashString(
- canonicalJson(proposalResp.contract_terms),
- );
-
- const parsedContractTerms = codecForContractTerms().decode(
- proposalResp.contract_terms,
- );
- const fulfillmentUrl = parsedContractTerms.fulfillment_url;
-
- await ws.db.runWithWriteTransaction(
- [Stores.proposals, Stores.purchases],
- async (tx) => {
- const p = await tx.get(Stores.proposals, proposalId);
- if (!p) {
- return;
- }
- if (p.proposalStatus !== ProposalStatus.DOWNLOADING) {
- return;
- }
- const amount = Amounts.parseOrThrow(parsedContractTerms.amount);
- let maxWireFee: AmountJson;
- if (parsedContractTerms.max_wire_fee) {
- maxWireFee = Amounts.parseOrThrow(parsedContractTerms.max_wire_fee);
- } else {
- maxWireFee = Amounts.getZero(amount.currency);
- }
- p.download = {
- contractData: {
- amount,
- contractTermsHash: contractTermsHash,
- fulfillmentUrl: parsedContractTerms.fulfillment_url,
- merchantBaseUrl: parsedContractTerms.merchant_base_url,
- merchantPub: parsedContractTerms.merchant_pub,
- merchantSig: proposalResp.sig,
- orderId: parsedContractTerms.order_id,
- summary: parsedContractTerms.summary,
- autoRefund: parsedContractTerms.auto_refund,
- maxWireFee,
- payDeadline: parsedContractTerms.pay_deadline,
- refundDeadline: parsedContractTerms.refund_deadline,
- wireFeeAmortization: parsedContractTerms.wire_fee_amortization || 1,
- allowedAuditors: parsedContractTerms.auditors.map((x) => ({
- auditorBaseUrl: x.url,
- auditorPub: x.master_pub,
- })),
- allowedExchanges: parsedContractTerms.exchanges.map((x) => ({
- exchangeBaseUrl: x.url,
- exchangePub: x.master_pub,
- })),
- timestamp: parsedContractTerms.timestamp,
- wireMethod: parsedContractTerms.wire_method,
- wireInfoHash: parsedContractTerms.h_wire,
- maxDepositFee: Amounts.parseOrThrow(parsedContractTerms.max_fee),
- merchant: parsedContractTerms.merchant,
- products: parsedContractTerms.products,
- summaryI18n: parsedContractTerms.summary_i18n,
- },
- contractTermsRaw: JSON.stringify(proposalResp.contract_terms),
- };
- if (
- fulfillmentUrl.startsWith("http://") ||
- fulfillmentUrl.startsWith("https://")
- ) {
- const differentPurchase = await tx.getIndexed(
- Stores.purchases.fulfillmentUrlIndex,
- fulfillmentUrl,
- );
- if (differentPurchase) {
- console.log("repurchase detected");
- p.proposalStatus = ProposalStatus.REPURCHASE;
- p.repurchaseProposalId = differentPurchase.proposalId;
- await tx.put(Stores.proposals, p);
- return;
- }
- }
- p.proposalStatus = ProposalStatus.PROPOSED;
- await tx.put(Stores.proposals, p);
- },
- );
-
- ws.notify({
- type: NotificationType.ProposalDownloaded,
- proposalId: proposal.proposalId,
- });
-}
-
-/**
- * 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 startDownloadProposal(
- ws: InternalWalletState,
- merchantBaseUrl: string,
- orderId: string,
- sessionId: string | undefined,
- claimToken: string | undefined,
-): Promise<string> {
- const oldProposal = await ws.db.getIndexed(
- Stores.proposals.urlAndOrderIdIndex,
- [merchantBaseUrl, orderId],
- );
- if (oldProposal) {
- await processDownloadProposal(ws, oldProposal.proposalId);
- return oldProposal.proposalId;
- }
-
- const { priv, pub } = await ws.cryptoApi.createEddsaKeypair();
- const proposalId = encodeCrock(getRandomBytes(32));
-
- const proposalRecord: ProposalRecord = {
- download: undefined,
- noncePriv: priv,
- noncePub: pub,
- claimToken,
- timestamp: getTimestampNow(),
- merchantBaseUrl,
- orderId,
- proposalId: proposalId,
- proposalStatus: ProposalStatus.DOWNLOADING,
- repurchaseProposalId: undefined,
- retryInfo: initRetryInfo(),
- lastError: undefined,
- downloadSessionId: sessionId,
- };
-
- await ws.db.runWithWriteTransaction([Stores.proposals], async (tx) => {
- const existingRecord = await tx.getIndexed(
- Stores.proposals.urlAndOrderIdIndex,
- [merchantBaseUrl, orderId],
- );
- if (existingRecord) {
- // Created concurrently
- return;
- }
- await tx.put(Stores.proposals, proposalRecord);
- });
-
- await processDownloadProposal(ws, proposalId);
- return proposalId;
-}
-
-export async function submitPay(
- ws: InternalWalletState,
- proposalId: string,
-): Promise<ConfirmPayResult> {
- const purchase = await ws.db.get(Stores.purchases, proposalId);
- if (!purchase) {
- throw Error("Purchase not found: " + proposalId);
- }
- if (purchase.abortRequested) {
- throw Error("not submitting payment for aborted purchase");
- }
- const sessionId = purchase.lastSessionId;
-
- console.log("paying with session ID", sessionId);
-
- const payUrl = new URL(
- `orders/${purchase.contractData.orderId}/pay`,
- purchase.contractData.merchantBaseUrl,
- ).href;
-
- const reqBody = {
- coins: purchase.coinDepositPermissions,
- session_id: purchase.lastSessionId,
- };
-
- logger.trace("making pay request", JSON.stringify(reqBody, undefined, 2));
-
- const resp = await ws.http.postJson(payUrl, reqBody);
-
- const merchantResp = await readSuccessResponseJsonOrThrow(
- resp,
- codecForMerchantPayResponse(),
- );
-
- logger.trace("got success from pay URL", merchantResp);
-
- const now = getTimestampNow();
-
- const merchantPub = purchase.contractData.merchantPub;
- const valid: boolean = await ws.cryptoApi.isValidPaymentSignature(
- merchantResp.sig,
- purchase.contractData.contractTermsHash,
- merchantPub,
- );
- if (!valid) {
- console.error("merchant payment signature invalid");
- // FIXME: properly display error
- throw Error("merchant payment signature invalid");
- }
- const isFirst = purchase.timestampFirstSuccessfulPay === undefined;
- purchase.timestampFirstSuccessfulPay = now;
- purchase.paymentSubmitPending = false;
- purchase.lastPayError = undefined;
- purchase.payRetryInfo = initRetryInfo(false);
- if (isFirst) {
- const ar = purchase.contractData.autoRefund;
- if (ar) {
- console.log("auto_refund present");
- purchase.refundStatusRequested = true;
- purchase.refundStatusRetryInfo = initRetryInfo();
- purchase.lastRefundStatusError = undefined;
- purchase.autoRefundDeadline = timestampAddDuration(now, ar);
- }
- }
-
- await ws.db.runWithWriteTransaction(
- [Stores.purchases, Stores.payEvents],
- async (tx) => {
- await tx.put(Stores.purchases, purchase);
- const payEvent: PayEventRecord = {
- proposalId,
- sessionId,
- timestamp: now,
- isReplay: !isFirst,
- };
- await tx.put(Stores.payEvents, payEvent);
- },
- );
-
- const nextUrl = getNextUrl(purchase.contractData);
- ws.cachedNextUrl[purchase.contractData.fulfillmentUrl] = {
- 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 preparePayForUri(
- ws: InternalWalletState,
- talerPayUri: string,
-): Promise<PreparePayResult> {
- const uriResult = parsePayUri(talerPayUri);
-
- if (!uriResult) {
- throw OperationFailedError.fromCode(
- TalerErrorCode.WALLET_INVALID_TALER_PAY_URI,
- `invalid taler://pay URI (${talerPayUri})`,
- {
- talerPayUri,
- },
- );
- }
-
- let proposalId = await startDownloadProposal(
- ws,
- uriResult.merchantBaseUrl,
- uriResult.orderId,
- uriResult.sessionId,
- uriResult.claimToken,
- );
-
- let proposal = await ws.db.get(Stores.proposals, proposalId);
- if (!proposal) {
- throw Error(`could not get proposal ${proposalId}`);
- }
- if (proposal.proposalStatus === ProposalStatus.REPURCHASE) {
- const existingProposalId = proposal.repurchaseProposalId;
- if (!existingProposalId) {
- throw Error("invalid proposal state");
- }
- console.log("using existing purchase for same product");
- proposal = await ws.db.get(Stores.proposals, existingProposalId);
- if (!proposal) {
- throw Error("existing proposal is in wrong state");
- }
- }
- const d = proposal.download;
- if (!d) {
- console.error("bad proposal", proposal);
- throw Error("proposal is in invalid state");
- }
- const contractData = d.contractData;
- const merchantSig = d.contractData.merchantSig;
- if (!merchantSig) {
- throw Error("BUG: proposal is in invalid state");
- }
-
- proposalId = proposal.proposalId;
-
- // First check if we already payed for it.
- const purchase = await ws.db.get(Stores.purchases, proposalId);
-
- if (!purchase) {
- // If not already paid, check if we could pay for it.
- const res = await getCoinsForPayment(ws, contractData);
-
- if (!res) {
- logger.info("not confirming payment, insufficient coins");
- return {
- status: PreparePayResultType.InsufficientBalance,
- contractTerms: JSON.parse(d.contractTermsRaw),
- proposalId: proposal.proposalId,
- };
- }
-
- const costInfo = await getTotalPaymentCost(ws, res);
- logger.trace("costInfo", costInfo);
- logger.trace("coinsForPayment", res);
-
- return {
- status: PreparePayResultType.PaymentPossible,
- contractTerms: JSON.parse(d.contractTermsRaw),
- proposalId: proposal.proposalId,
- amountEffective: Amounts.stringify(costInfo.totalCost),
- amountRaw: Amounts.stringify(res.paymentAmount),
- };
- }
-
- if (purchase.lastSessionId !== uriResult.sessionId) {
- logger.trace(
- "automatically re-submitting payment with different session ID",
- );
- await ws.db.runWithWriteTransaction([Stores.purchases], async (tx) => {
- const p = await tx.get(Stores.purchases, proposalId);
- if (!p) {
- return;
- }
- p.lastSessionId = uriResult.sessionId;
- await tx.put(Stores.purchases, p);
- });
- const r = await submitPay(ws, proposalId);
- return {
- status: PreparePayResultType.AlreadyConfirmed,
- contractTerms: JSON.parse(purchase.contractTermsRaw),
- paid: true,
- nextUrl: r.nextUrl,
- };
- } else if (!purchase.timestampFirstSuccessfulPay) {
- return {
- status: PreparePayResultType.AlreadyConfirmed,
- contractTerms: JSON.parse(purchase.contractTermsRaw),
- paid: false,
- };
- } else if (purchase.paymentSubmitPending) {
- return {
- status: PreparePayResultType.AlreadyConfirmed,
- contractTerms: JSON.parse(purchase.contractTermsRaw),
- paid: false,
- };
- }
- // FIXME: we don't handle aborted payments correctly here.
- throw Error("BUG: invariant violation (purchase status)");
-}
-
-/**
- * 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 ws.db.get(Stores.proposals, proposalId);
-
- if (!proposal) {
- throw Error(`proposal with id ${proposalId} not found`);
- }
-
- const d = proposal.download;
- if (!d) {
- throw Error("proposal is in invalid state");
- }
-
- let purchase = await ws.db.get(
- Stores.purchases,
- d.contractData.contractTermsHash,
- );
-
- if (purchase) {
- if (
- sessionIdOverride !== undefined &&
- sessionIdOverride != purchase.lastSessionId
- ) {
- logger.trace(`changing session ID to ${sessionIdOverride}`);
- await ws.db.mutate(Stores.purchases, purchase.proposalId, (x) => {
- x.lastSessionId = sessionIdOverride;
- x.paymentSubmitPending = true;
- return x;
- });
- }
- logger.trace("confirmPay: submitting payment for existing purchase");
- return submitPay(ws, proposalId);
- }
-
- logger.trace("confirmPay: purchase record does not exist yet");
-
- const res = await getCoinsForPayment(ws, d.contractData);
-
- logger.trace("coin selection result", res);
-
- if (!res) {
- // Should not happen, since checkPay should be called first
- logger.warn("not confirming payment, insufficient coins");
- throw Error("insufficient balance");
- }
-
- const depositPermissions: CoinDepositPermission[] = [];
- for (let i = 0; i < res.coinPubs.length; i++) {
- const coin = await ws.db.get(Stores.coins, res.coinPubs[i]);
- if (!coin) {
- throw Error("can't pay, allocated coin not found anymore");
- }
- const denom = await ws.db.get(Stores.denominations, [
- coin.exchangeBaseUrl,
- coin.denomPub,
- ]);
- if (!denom) {
- throw Error(
- "can't pay, denomination of allocated coin not found anymore",
- );
- }
- const dp = await ws.cryptoApi.signDepositPermission({
- coinPriv: coin.coinPriv,
- coinPub: coin.coinPub,
- contractTermsHash: d.contractData.contractTermsHash,
- denomPubHash: coin.denomPubHash,
- denomSig: coin.denomSig,
- exchangeBaseUrl: coin.exchangeBaseUrl,
- feeDeposit: denom.feeDeposit,
- merchantPub: d.contractData.merchantPub,
- refundDeadline: d.contractData.refundDeadline,
- spendAmount: res.coinContributions[i],
- timestamp: d.contractData.timestamp,
- wireInfoHash: d.contractData.wireInfoHash,
- });
- depositPermissions.push(dp);
- }
- purchase = await recordConfirmPay(
- ws,
- proposal,
- res,
- depositPermissions,
- sessionIdOverride,
- );
-
- return submitPay(ws, proposalId);
-}
-
-export async function processPurchasePay(
- ws: InternalWalletState,
- proposalId: string,
- forceNow = false,
-): Promise<void> {
- const onOpErr = (e: OperationErrorDetails): Promise<void> =>
- incrementPurchasePayRetry(ws, proposalId, e);
- await guardOperationException(
- () => processPurchasePayImpl(ws, proposalId, forceNow),
- onOpErr,
- );
-}
-
-async function resetPurchasePayRetry(
- ws: InternalWalletState,
- proposalId: string,
-): Promise<void> {
- await ws.db.mutate(Stores.purchases, proposalId, (x) => {
- if (x.payRetryInfo.active) {
- x.payRetryInfo = initRetryInfo();
- }
- return x;
- });
-}
-
-async function processPurchasePayImpl(
- ws: InternalWalletState,
- proposalId: string,
- forceNow: boolean,
-): Promise<void> {
- if (forceNow) {
- await resetPurchasePayRetry(ws, proposalId);
- }
- const purchase = await ws.db.get(Stores.purchases, proposalId);
- if (!purchase) {
- return;
- }
- if (!purchase.paymentSubmitPending) {
- return;
- }
- logger.trace(`processing purchase pay ${proposalId}`);
- await submitPay(ws, proposalId);
-}
-
-export async function refuseProposal(
- ws: InternalWalletState,
- proposalId: string,
-): Promise<void> {
- const success = await ws.db.runWithWriteTransaction(
- [Stores.proposals],
- async (tx) => {
- const proposal = await tx.get(Stores.proposals, proposalId);
- if (!proposal) {
- logger.trace(`proposal ${proposalId} not found, won't refuse proposal`);
- return false;
- }
- if (proposal.proposalStatus !== ProposalStatus.PROPOSED) {
- return false;
- }
- proposal.proposalStatus = ProposalStatus.REFUSED;
- await tx.put(Stores.proposals, proposal);
- return true;
- },
- );
- if (success) {
- ws.notify({
- type: NotificationType.ProposalRefused,
- });
- }
-}
diff --git a/src/operations/pending.ts b/src/operations/pending.ts
deleted file mode 100644
index acad5e634..000000000
--- a/src/operations/pending.ts
+++ /dev/null
@@ -1,458 +0,0 @@
-/*
- 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/>
- */
-
-/**
- * Imports.
- */
-import {
- ExchangeUpdateStatus,
- ProposalStatus,
- ReserveRecordStatus,
- Stores,
-} from "../types/dbTypes";
-import {
- PendingOperationsResponse,
- PendingOperationType,
- ExchangeUpdateOperationStage,
- ReserveType,
-} from "../types/pending";
-import {
- Duration,
- getTimestampNow,
- Timestamp,
- getDurationRemaining,
- durationMin,
-} from "../util/time";
-import { TransactionHandle } from "../util/query";
-import { InternalWalletState } from "./state";
-import { getBalancesInsideTransaction } from "./balance";
-
-function updateRetryDelay(
- oldDelay: Duration,
- now: Timestamp,
- retryTimestamp: Timestamp,
-): Duration {
- const remaining = getDurationRemaining(retryTimestamp, now);
- const nextDelay = durationMin(oldDelay, remaining);
- return nextDelay;
-}
-
-async function gatherExchangePending(
- tx: TransactionHandle,
- now: Timestamp,
- resp: PendingOperationsResponse,
- onlyDue = false,
-): Promise<void> {
- if (onlyDue) {
- // FIXME: exchanges should also be updated regularly
- return;
- }
- await tx.iter(Stores.exchanges).forEach((e) => {
- switch (e.updateStatus) {
- case ExchangeUpdateStatus.Finished:
- if (e.lastError) {
- resp.pendingOperations.push({
- type: PendingOperationType.Bug,
- givesLifeness: false,
- message:
- "Exchange record is in FINISHED state but has lastError set",
- details: {
- exchangeBaseUrl: e.baseUrl,
- },
- });
- }
- if (!e.details) {
- resp.pendingOperations.push({
- type: PendingOperationType.Bug,
- givesLifeness: false,
- message:
- "Exchange record does not have details, but no update in progress.",
- details: {
- exchangeBaseUrl: e.baseUrl,
- },
- });
- }
- if (!e.wireInfo) {
- resp.pendingOperations.push({
- type: PendingOperationType.Bug,
- givesLifeness: false,
- message:
- "Exchange record does not have wire info, but no update in progress.",
- details: {
- exchangeBaseUrl: e.baseUrl,
- },
- });
- }
- break;
- case ExchangeUpdateStatus.FetchKeys:
- resp.pendingOperations.push({
- type: PendingOperationType.ExchangeUpdate,
- givesLifeness: false,
- stage: ExchangeUpdateOperationStage.FetchKeys,
- exchangeBaseUrl: e.baseUrl,
- lastError: e.lastError,
- reason: e.updateReason || "unknown",
- });
- break;
- case ExchangeUpdateStatus.FetchWire:
- resp.pendingOperations.push({
- type: PendingOperationType.ExchangeUpdate,
- givesLifeness: false,
- stage: ExchangeUpdateOperationStage.FetchWire,
- exchangeBaseUrl: e.baseUrl,
- lastError: e.lastError,
- reason: e.updateReason || "unknown",
- });
- break;
- case ExchangeUpdateStatus.FinalizeUpdate:
- resp.pendingOperations.push({
- type: PendingOperationType.ExchangeUpdate,
- givesLifeness: false,
- stage: ExchangeUpdateOperationStage.FinalizeUpdate,
- exchangeBaseUrl: e.baseUrl,
- lastError: e.lastError,
- reason: e.updateReason || "unknown",
- });
- break;
- default:
- resp.pendingOperations.push({
- type: PendingOperationType.Bug,
- givesLifeness: false,
- message: "Unknown exchangeUpdateStatus",
- details: {
- exchangeBaseUrl: e.baseUrl,
- exchangeUpdateStatus: e.updateStatus,
- },
- });
- break;
- }
- });
-}
-
-async function gatherReservePending(
- tx: TransactionHandle,
- now: Timestamp,
- resp: PendingOperationsResponse,
- onlyDue = false,
-): Promise<void> {
- // FIXME: this should be optimized by using an index for "onlyDue==true".
- await tx.iter(Stores.reserves).forEach((reserve) => {
- const reserveType = reserve.bankInfo
- ? ReserveType.TalerBankWithdraw
- : ReserveType.Manual;
- if (!reserve.retryInfo.active) {
- return;
- }
- switch (reserve.reserveStatus) {
- case ReserveRecordStatus.DORMANT:
- // nothing to report as pending
- break;
- case ReserveRecordStatus.WAIT_CONFIRM_BANK:
- case ReserveRecordStatus.WITHDRAWING:
- case ReserveRecordStatus.QUERYING_STATUS:
- case ReserveRecordStatus.REGISTERING_BANK:
- resp.nextRetryDelay = updateRetryDelay(
- resp.nextRetryDelay,
- now,
- reserve.retryInfo.nextRetry,
- );
- if (onlyDue && reserve.retryInfo.nextRetry.t_ms > now.t_ms) {
- return;
- }
- resp.pendingOperations.push({
- type: PendingOperationType.Reserve,
- givesLifeness: true,
- stage: reserve.reserveStatus,
- timestampCreated: reserve.timestampCreated,
- reserveType,
- reservePub: reserve.reservePub,
- retryInfo: reserve.retryInfo,
- });
- break;
- default:
- resp.pendingOperations.push({
- type: PendingOperationType.Bug,
- givesLifeness: false,
- message: "Unknown reserve record status",
- details: {
- reservePub: reserve.reservePub,
- reserveStatus: reserve.reserveStatus,
- },
- });
- break;
- }
- });
-}
-
-async function gatherRefreshPending(
- tx: TransactionHandle,
- now: Timestamp,
- resp: PendingOperationsResponse,
- onlyDue = false,
-): Promise<void> {
- await tx.iter(Stores.refreshGroups).forEach((r) => {
- if (r.timestampFinished) {
- return;
- }
- resp.nextRetryDelay = updateRetryDelay(
- resp.nextRetryDelay,
- now,
- r.retryInfo.nextRetry,
- );
- if (onlyDue && r.retryInfo.nextRetry.t_ms > now.t_ms) {
- return;
- }
-
- resp.pendingOperations.push({
- type: PendingOperationType.Refresh,
- givesLifeness: true,
- refreshGroupId: r.refreshGroupId,
- finishedPerCoin: r.finishedPerCoin,
- retryInfo: r.retryInfo,
- });
- });
-}
-
-async function gatherWithdrawalPending(
- tx: TransactionHandle,
- now: Timestamp,
- resp: PendingOperationsResponse,
- onlyDue = false,
-): Promise<void> {
- await tx.iter(Stores.withdrawalGroups).forEachAsync(async (wsr) => {
- if (wsr.timestampFinish) {
- return;
- }
- resp.nextRetryDelay = updateRetryDelay(
- resp.nextRetryDelay,
- now,
- wsr.retryInfo.nextRetry,
- );
- if (onlyDue && wsr.retryInfo.nextRetry.t_ms > now.t_ms) {
- return;
- }
- let numCoinsWithdrawn = 0;
- let numCoinsTotal = 0;
- await tx
- .iterIndexed(Stores.planchets.byGroup, wsr.withdrawalGroupId)
- .forEach((x) => {
- numCoinsTotal++;
- if (x.withdrawalDone) {
- numCoinsWithdrawn++;
- }
- });
- resp.pendingOperations.push({
- type: PendingOperationType.Withdraw,
- givesLifeness: true,
- numCoinsTotal,
- numCoinsWithdrawn,
- source: wsr.source,
- withdrawalGroupId: wsr.withdrawalGroupId,
- lastError: wsr.lastError,
- });
- });
-}
-
-async function gatherProposalPending(
- tx: TransactionHandle,
- now: Timestamp,
- resp: PendingOperationsResponse,
- onlyDue = false,
-): Promise<void> {
- await tx.iter(Stores.proposals).forEach((proposal) => {
- if (proposal.proposalStatus == ProposalStatus.PROPOSED) {
- if (onlyDue) {
- return;
- }
- const dl = proposal.download;
- if (!dl) {
- resp.pendingOperations.push({
- type: PendingOperationType.Bug,
- message: "proposal is in invalid state",
- details: {},
- givesLifeness: false,
- });
- } else {
- resp.pendingOperations.push({
- type: PendingOperationType.ProposalChoice,
- givesLifeness: false,
- merchantBaseUrl: dl.contractData.merchantBaseUrl,
- proposalId: proposal.proposalId,
- proposalTimestamp: proposal.timestamp,
- });
- }
- } else if (proposal.proposalStatus == ProposalStatus.DOWNLOADING) {
- resp.nextRetryDelay = updateRetryDelay(
- resp.nextRetryDelay,
- now,
- proposal.retryInfo.nextRetry,
- );
- if (onlyDue && proposal.retryInfo.nextRetry.t_ms > now.t_ms) {
- return;
- }
- resp.pendingOperations.push({
- type: PendingOperationType.ProposalDownload,
- givesLifeness: true,
- merchantBaseUrl: proposal.merchantBaseUrl,
- orderId: proposal.orderId,
- proposalId: proposal.proposalId,
- proposalTimestamp: proposal.timestamp,
- lastError: proposal.lastError,
- retryInfo: proposal.retryInfo,
- });
- }
- });
-}
-
-async function gatherTipPending(
- tx: TransactionHandle,
- now: Timestamp,
- resp: PendingOperationsResponse,
- onlyDue = false,
-): Promise<void> {
- await tx.iter(Stores.tips).forEach((tip) => {
- if (tip.pickedUp) {
- return;
- }
- resp.nextRetryDelay = updateRetryDelay(
- resp.nextRetryDelay,
- now,
- tip.retryInfo.nextRetry,
- );
- if (onlyDue && tip.retryInfo.nextRetry.t_ms > now.t_ms) {
- return;
- }
- if (tip.acceptedTimestamp) {
- resp.pendingOperations.push({
- type: PendingOperationType.TipPickup,
- givesLifeness: true,
- merchantBaseUrl: tip.merchantBaseUrl,
- tipId: tip.tipId,
- merchantTipId: tip.merchantTipId,
- });
- }
- });
-}
-
-async function gatherPurchasePending(
- tx: TransactionHandle,
- now: Timestamp,
- resp: PendingOperationsResponse,
- onlyDue = false,
-): Promise<void> {
- await tx.iter(Stores.purchases).forEach((pr) => {
- if (pr.paymentSubmitPending) {
- resp.nextRetryDelay = updateRetryDelay(
- resp.nextRetryDelay,
- now,
- pr.payRetryInfo.nextRetry,
- );
- if (!onlyDue || pr.payRetryInfo.nextRetry.t_ms <= now.t_ms) {
- resp.pendingOperations.push({
- type: PendingOperationType.Pay,
- givesLifeness: true,
- isReplay: false,
- proposalId: pr.proposalId,
- retryInfo: pr.payRetryInfo,
- lastError: pr.lastPayError,
- });
- }
- }
- if (pr.refundStatusRequested) {
- resp.nextRetryDelay = updateRetryDelay(
- resp.nextRetryDelay,
- now,
- pr.refundStatusRetryInfo.nextRetry,
- );
- if (!onlyDue || pr.refundStatusRetryInfo.nextRetry.t_ms <= now.t_ms) {
- resp.pendingOperations.push({
- type: PendingOperationType.RefundQuery,
- givesLifeness: true,
- proposalId: pr.proposalId,
- retryInfo: pr.refundStatusRetryInfo,
- lastError: pr.lastRefundStatusError,
- });
- }
- }
- });
-}
-
-async function gatherRecoupPending(
- tx: TransactionHandle,
- now: Timestamp,
- resp: PendingOperationsResponse,
- onlyDue = false,
-): Promise<void> {
- await tx.iter(Stores.recoupGroups).forEach((rg) => {
- if (rg.timestampFinished) {
- return;
- }
- resp.nextRetryDelay = updateRetryDelay(
- resp.nextRetryDelay,
- now,
- rg.retryInfo.nextRetry,
- );
- if (onlyDue && rg.retryInfo.nextRetry.t_ms > now.t_ms) {
- return;
- }
- resp.pendingOperations.push({
- type: PendingOperationType.Recoup,
- givesLifeness: true,
- recoupGroupId: rg.recoupGroupId,
- retryInfo: rg.retryInfo,
- lastError: rg.lastError,
- });
- });
-}
-
-export async function getPendingOperations(
- ws: InternalWalletState,
- { onlyDue = false } = {},
-): Promise<PendingOperationsResponse> {
- const now = getTimestampNow();
- return await ws.db.runWithReadTransaction(
- [
- Stores.exchanges,
- Stores.reserves,
- Stores.refreshGroups,
- Stores.coins,
- Stores.withdrawalGroups,
- Stores.proposals,
- Stores.tips,
- Stores.purchases,
- Stores.recoupGroups,
- Stores.planchets,
- ],
- async (tx) => {
- const walletBalance = await getBalancesInsideTransaction(ws, tx);
- const resp: PendingOperationsResponse = {
- nextRetryDelay: { d_ms: Number.MAX_SAFE_INTEGER },
- onlyDue: onlyDue,
- walletBalance,
- pendingOperations: [],
- };
- await gatherExchangePending(tx, now, resp, onlyDue);
- await gatherReservePending(tx, now, resp, onlyDue);
- await gatherRefreshPending(tx, now, resp, onlyDue);
- await gatherWithdrawalPending(tx, now, resp, onlyDue);
- await gatherProposalPending(tx, now, resp, onlyDue);
- await gatherTipPending(tx, now, resp, onlyDue);
- await gatherPurchasePending(tx, now, resp, onlyDue);
- await gatherRecoupPending(tx, now, resp, onlyDue);
- return resp;
- },
- );
-}
diff --git a/src/operations/recoup.ts b/src/operations/recoup.ts
deleted file mode 100644
index e5f14c6ee..000000000
--- a/src/operations/recoup.ts
+++ /dev/null
@@ -1,411 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2019-2020 Taler Systems SA
-
- 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/>
- */
-
-/**
- * Implementation of the recoup operation, which allows to recover the
- * value of coins held in a revoked denomination.
- *
- * @author Florian Dold <dold@taler.net>
- */
-
-/**
- * Imports.
- */
-import { InternalWalletState } from "./state";
-import {
- Stores,
- CoinStatus,
- CoinSourceType,
- CoinRecord,
- WithdrawCoinSource,
- RefreshCoinSource,
- ReserveRecordStatus,
- RecoupGroupRecord,
- initRetryInfo,
- updateRetryInfoTimeout,
-} from "../types/dbTypes";
-
-import { codecForRecoupConfirmation } from "../types/talerTypes";
-import { NotificationType } from "../types/notifications";
-import { forceQueryReserve } from "./reserves";
-
-import { Amounts } from "../util/amounts";
-import { createRefreshGroup, processRefreshGroup } from "./refresh";
-import { RefreshReason, OperationErrorDetails } from "../types/walletTypes";
-import { TransactionHandle } from "../util/query";
-import { encodeCrock, getRandomBytes } from "../crypto/talerCrypto";
-import { getTimestampNow } from "../util/time";
-import { guardOperationException } from "./errors";
-import { readSuccessResponseJsonOrThrow } from "../util/http";
-
-async function incrementRecoupRetry(
- ws: InternalWalletState,
- recoupGroupId: string,
- err: OperationErrorDetails | undefined,
-): Promise<void> {
- await ws.db.runWithWriteTransaction([Stores.recoupGroups], async (tx) => {
- const r = await tx.get(Stores.recoupGroups, recoupGroupId);
- if (!r) {
- return;
- }
- if (!r.retryInfo) {
- return;
- }
- r.retryInfo.retryCounter++;
- updateRetryInfoTimeout(r.retryInfo);
- r.lastError = err;
- await tx.put(Stores.recoupGroups, r);
- });
- if (err) {
- ws.notify({ type: NotificationType.RecoupOperationError, error: err });
- }
-}
-
-async function putGroupAsFinished(
- ws: InternalWalletState,
- tx: TransactionHandle,
- recoupGroup: RecoupGroupRecord,
- coinIdx: number,
-): Promise<void> {
- if (recoupGroup.timestampFinished) {
- return;
- }
- recoupGroup.recoupFinishedPerCoin[coinIdx] = true;
- let allFinished = true;
- for (const b of recoupGroup.recoupFinishedPerCoin) {
- if (!b) {
- allFinished = false;
- }
- }
- if (allFinished) {
- recoupGroup.timestampFinished = getTimestampNow();
- recoupGroup.retryInfo = initRetryInfo(false);
- recoupGroup.lastError = undefined;
- if (recoupGroup.scheduleRefreshCoins.length > 0) {
- const refreshGroupId = await createRefreshGroup(
- ws,
- tx,
- recoupGroup.scheduleRefreshCoins.map((x) => ({ coinPub: x })),
- RefreshReason.Recoup,
- );
- processRefreshGroup(ws, refreshGroupId.refreshGroupId).then((e) => {
- console.error("error while refreshing after recoup", e);
- });
- }
- }
- await tx.put(Stores.recoupGroups, recoupGroup);
-}
-
-async function recoupTipCoin(
- ws: InternalWalletState,
- recoupGroupId: string,
- coinIdx: number,
- coin: CoinRecord,
-): Promise<void> {
- // We can't really recoup a coin we got via tipping.
- // Thus we just put the coin to sleep.
- // FIXME: somehow report this to the user
- await ws.db.runWithWriteTransaction([Stores.recoupGroups], async (tx) => {
- const recoupGroup = await tx.get(Stores.recoupGroups, recoupGroupId);
- if (!recoupGroup) {
- return;
- }
- if (recoupGroup.recoupFinishedPerCoin[coinIdx]) {
- return;
- }
- await putGroupAsFinished(ws, tx, recoupGroup, coinIdx);
- });
-}
-
-async function recoupWithdrawCoin(
- ws: InternalWalletState,
- recoupGroupId: string,
- coinIdx: number,
- coin: CoinRecord,
- cs: WithdrawCoinSource,
-): Promise<void> {
- const reservePub = cs.reservePub;
- const reserve = await ws.db.get(Stores.reserves, reservePub);
- if (!reserve) {
- // FIXME: We should at least emit some pending operation / warning for this?
- return;
- }
-
- ws.notify({
- type: NotificationType.RecoupStarted,
- });
-
- const recoupRequest = await ws.cryptoApi.createRecoupRequest(coin);
- const reqUrl = new URL(`/coins/${coin.coinPub}/recoup`, coin.exchangeBaseUrl);
- const resp = await ws.http.postJson(reqUrl.href, recoupRequest);
- const recoupConfirmation = await readSuccessResponseJsonOrThrow(
- resp,
- codecForRecoupConfirmation(),
- );
-
- if (recoupConfirmation.reserve_pub !== reservePub) {
- throw Error(`Coin's reserve doesn't match reserve on recoup`);
- }
-
- const exchange = await ws.db.get(Stores.exchanges, coin.exchangeBaseUrl);
- if (!exchange) {
- // FIXME: report inconsistency?
- return;
- }
- const exchangeDetails = exchange.details;
- if (!exchangeDetails) {
- // FIXME: report inconsistency?
- return;
- }
-
- // FIXME: verify that our expectations about the amount match
-
- await ws.db.runWithWriteTransaction(
- [Stores.coins, Stores.reserves, Stores.recoupGroups],
- async (tx) => {
- const recoupGroup = await tx.get(Stores.recoupGroups, recoupGroupId);
- if (!recoupGroup) {
- return;
- }
- if (recoupGroup.recoupFinishedPerCoin[coinIdx]) {
- return;
- }
- const updatedCoin = await tx.get(Stores.coins, coin.coinPub);
- if (!updatedCoin) {
- return;
- }
- const updatedReserve = await tx.get(Stores.reserves, reserve.reservePub);
- if (!updatedReserve) {
- return;
- }
- updatedCoin.status = CoinStatus.Dormant;
- const currency = updatedCoin.currentAmount.currency;
- updatedCoin.currentAmount = Amounts.getZero(currency);
- updatedReserve.reserveStatus = ReserveRecordStatus.QUERYING_STATUS;
- await tx.put(Stores.coins, updatedCoin);
- await tx.put(Stores.reserves, updatedReserve);
- await putGroupAsFinished(ws, tx, recoupGroup, coinIdx);
- },
- );
-
- ws.notify({
- type: NotificationType.RecoupFinished,
- });
-
- forceQueryReserve(ws, reserve.reservePub).catch((e) => {
- console.log("re-querying reserve after recoup failed:", e);
- });
-}
-
-async function recoupRefreshCoin(
- ws: InternalWalletState,
- recoupGroupId: string,
- coinIdx: number,
- coin: CoinRecord,
- cs: RefreshCoinSource,
-): Promise<void> {
- ws.notify({
- type: NotificationType.RecoupStarted,
- });
-
- const recoupRequest = await ws.cryptoApi.createRecoupRequest(coin);
- const reqUrl = new URL(`/coins/${coin.coinPub}/recoup`, coin.exchangeBaseUrl);
- console.log("making recoup request");
-
- const resp = await ws.http.postJson(reqUrl.href, recoupRequest);
- const recoupConfirmation = await readSuccessResponseJsonOrThrow(
- resp,
- codecForRecoupConfirmation(),
- );
-
- if (recoupConfirmation.old_coin_pub != cs.oldCoinPub) {
- throw Error(`Coin's oldCoinPub doesn't match reserve on recoup`);
- }
-
- const exchange = await ws.db.get(Stores.exchanges, coin.exchangeBaseUrl);
- if (!exchange) {
- // FIXME: report inconsistency?
- return;
- }
- const exchangeDetails = exchange.details;
- if (!exchangeDetails) {
- // FIXME: report inconsistency?
- return;
- }
-
- await ws.db.runWithWriteTransaction(
- [Stores.coins, Stores.reserves, Stores.recoupGroups, Stores.refreshGroups],
- async (tx) => {
- const recoupGroup = await tx.get(Stores.recoupGroups, recoupGroupId);
- if (!recoupGroup) {
- return;
- }
- if (recoupGroup.recoupFinishedPerCoin[coinIdx]) {
- return;
- }
- const oldCoin = await tx.get(Stores.coins, cs.oldCoinPub);
- const revokedCoin = await tx.get(Stores.coins, coin.coinPub);
- if (!revokedCoin) {
- return;
- }
- if (!oldCoin) {
- return;
- }
- revokedCoin.status = CoinStatus.Dormant;
- oldCoin.currentAmount = Amounts.add(
- oldCoin.currentAmount,
- recoupGroup.oldAmountPerCoin[coinIdx],
- ).amount;
- console.log(
- "recoup: setting old coin amount to",
- Amounts.stringify(oldCoin.currentAmount),
- );
- recoupGroup.scheduleRefreshCoins.push(oldCoin.coinPub);
- await tx.put(Stores.coins, revokedCoin);
- await tx.put(Stores.coins, oldCoin);
- await putGroupAsFinished(ws, tx, recoupGroup, coinIdx);
- },
- );
-}
-
-async function resetRecoupGroupRetry(
- ws: InternalWalletState,
- recoupGroupId: string,
-): Promise<void> {
- await ws.db.mutate(Stores.recoupGroups, recoupGroupId, (x) => {
- if (x.retryInfo.active) {
- x.retryInfo = initRetryInfo();
- }
- return x;
- });
-}
-
-export async function processRecoupGroup(
- ws: InternalWalletState,
- recoupGroupId: string,
- forceNow = false,
-): Promise<void> {
- await ws.memoProcessRecoup.memo(recoupGroupId, async () => {
- const onOpErr = (e: OperationErrorDetails): Promise<void> =>
- incrementRecoupRetry(ws, recoupGroupId, e);
- return await guardOperationException(
- async () => await processRecoupGroupImpl(ws, recoupGroupId, forceNow),
- onOpErr,
- );
- });
-}
-
-async function processRecoupGroupImpl(
- ws: InternalWalletState,
- recoupGroupId: string,
- forceNow = false,
-): Promise<void> {
- if (forceNow) {
- await resetRecoupGroupRetry(ws, recoupGroupId);
- }
- console.log("in processRecoupGroupImpl");
- const recoupGroup = await ws.db.get(Stores.recoupGroups, recoupGroupId);
- if (!recoupGroup) {
- return;
- }
- console.log(recoupGroup);
- if (recoupGroup.timestampFinished) {
- console.log("recoup group finished");
- return;
- }
- const ps = recoupGroup.coinPubs.map((x, i) =>
- processRecoup(ws, recoupGroupId, i),
- );
- await Promise.all(ps);
-}
-
-export async function createRecoupGroup(
- ws: InternalWalletState,
- tx: TransactionHandle,
- coinPubs: string[],
-): Promise<string> {
- const recoupGroupId = encodeCrock(getRandomBytes(32));
-
- const recoupGroup: RecoupGroupRecord = {
- recoupGroupId,
- coinPubs: coinPubs,
- lastError: undefined,
- timestampFinished: undefined,
- timestampStarted: getTimestampNow(),
- retryInfo: initRetryInfo(),
- recoupFinishedPerCoin: coinPubs.map(() => false),
- // Will be populated later
- oldAmountPerCoin: [],
- scheduleRefreshCoins: [],
- };
-
- for (let coinIdx = 0; coinIdx < coinPubs.length; coinIdx++) {
- const coinPub = coinPubs[coinIdx];
- const coin = await tx.get(Stores.coins, coinPub);
- if (!coin) {
- await putGroupAsFinished(ws, tx, recoupGroup, coinIdx);
- continue;
- }
- if (Amounts.isZero(coin.currentAmount)) {
- await putGroupAsFinished(ws, tx, recoupGroup, coinIdx);
- continue;
- }
- recoupGroup.oldAmountPerCoin[coinIdx] = coin.currentAmount;
- coin.currentAmount = Amounts.getZero(coin.currentAmount.currency);
- await tx.put(Stores.coins, coin);
- }
-
- await tx.put(Stores.recoupGroups, recoupGroup);
-
- return recoupGroupId;
-}
-
-async function processRecoup(
- ws: InternalWalletState,
- recoupGroupId: string,
- coinIdx: number,
-): Promise<void> {
- const recoupGroup = await ws.db.get(Stores.recoupGroups, recoupGroupId);
- if (!recoupGroup) {
- return;
- }
- if (recoupGroup.timestampFinished) {
- return;
- }
- if (recoupGroup.recoupFinishedPerCoin[coinIdx]) {
- return;
- }
-
- const coinPub = recoupGroup.coinPubs[coinIdx];
-
- const coin = await ws.db.get(Stores.coins, coinPub);
- if (!coin) {
- throw Error(`Coin ${coinPub} not found, can't request payback`);
- }
-
- const cs = coin.coinSource;
-
- switch (cs.type) {
- case CoinSourceType.Tip:
- return recoupTipCoin(ws, recoupGroupId, coinIdx, coin);
- case CoinSourceType.Refresh:
- return recoupRefreshCoin(ws, recoupGroupId, coinIdx, coin, cs);
- case CoinSourceType.Withdraw:
- return recoupWithdrawCoin(ws, recoupGroupId, coinIdx, coin, cs);
- default:
- throw Error("unknown coin source type");
- }
-}
diff --git a/src/operations/refresh.ts b/src/operations/refresh.ts
deleted file mode 100644
index 74b032b91..000000000
--- a/src/operations/refresh.ts
+++ /dev/null
@@ -1,572 +0,0 @@
-/*
- 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 { Amounts, AmountJson } from "../util/amounts";
-import {
- DenominationRecord,
- Stores,
- CoinStatus,
- RefreshPlanchetRecord,
- CoinRecord,
- RefreshSessionRecord,
- initRetryInfo,
- updateRetryInfoTimeout,
- RefreshGroupRecord,
- CoinSourceType,
-} from "../types/dbTypes";
-import { amountToPretty } from "../util/helpers";
-import { TransactionHandle } from "../util/query";
-import { InternalWalletState } from "./state";
-import { Logger } from "../util/logging";
-import { getWithdrawDenomList } from "./withdraw";
-import { updateExchangeFromUrl } from "./exchanges";
-import {
- OperationErrorDetails,
- CoinPublicKey,
- RefreshReason,
- RefreshGroupId,
-} from "../types/walletTypes";
-import { guardOperationException } from "./errors";
-import { NotificationType } from "../types/notifications";
-import { getRandomBytes, encodeCrock } from "../crypto/talerCrypto";
-import { getTimestampNow } from "../util/time";
-import { readSuccessResponseJsonOrThrow } from "../util/http";
-import {
- codecForExchangeMeltResponse,
- codecForExchangeRevealResponse,
-} from "../types/talerTypes";
-
-const logger = new Logger("refresh.ts");
-
-/**
- * Get the amount that we lose when refreshing a coin of the given denomination
- * with a certain amount left.
- *
- * If the amount left is zero, then the refresh cost
- * is also considered to be zero. If a refresh isn't possible (e.g. due to lack of
- * the right denominations), then the cost is the full amount left.
- *
- * Considers refresh fees, withdrawal fees after refresh and amounts too small
- * to refresh.
- */
-export function getTotalRefreshCost(
- denoms: DenominationRecord[],
- refreshedDenom: DenominationRecord,
- amountLeft: AmountJson,
-): AmountJson {
- const withdrawAmount = Amounts.sub(amountLeft, refreshedDenom.feeRefresh)
- .amount;
- const withdrawDenoms = getWithdrawDenomList(withdrawAmount, denoms);
- const resultingAmount = Amounts.add(
- Amounts.getZero(withdrawAmount.currency),
- ...withdrawDenoms.selectedDenoms.map(
- (d) => Amounts.mult(d.denom.value, d.count).amount,
- ),
- ).amount;
- const totalCost = Amounts.sub(amountLeft, resultingAmount).amount;
- logger.trace(
- `total refresh cost for ${amountToPretty(amountLeft)} is ${amountToPretty(
- totalCost,
- )}`,
- );
- return totalCost;
-}
-
-/**
- * Create a refresh session inside a refresh group.
- */
-async function refreshCreateSession(
- ws: InternalWalletState,
- refreshGroupId: string,
- coinIndex: number,
-): Promise<void> {
- logger.trace(
- `creating refresh session for coin ${coinIndex} in refresh group ${refreshGroupId}`,
- );
- const refreshGroup = await ws.db.get(Stores.refreshGroups, refreshGroupId);
- if (!refreshGroup) {
- return;
- }
- if (refreshGroup.finishedPerCoin[coinIndex]) {
- return;
- }
- const existingRefreshSession = refreshGroup.refreshSessionPerCoin[coinIndex];
- if (existingRefreshSession) {
- return;
- }
- const oldCoinPub = refreshGroup.oldCoinPubs[coinIndex];
- const coin = await ws.db.get(Stores.coins, oldCoinPub);
- if (!coin) {
- throw Error("Can't refresh, coin not found");
- }
-
- const exchange = await updateExchangeFromUrl(ws, coin.exchangeBaseUrl);
- if (!exchange) {
- throw Error("db inconsistent: exchange of coin not found");
- }
-
- const oldDenom = await ws.db.get(Stores.denominations, [
- exchange.baseUrl,
- coin.denomPub,
- ]);
-
- if (!oldDenom) {
- throw Error("db inconsistent: denomination for coin not found");
- }
-
- const availableDenoms: DenominationRecord[] = await ws.db
- .iterIndex(Stores.denominations.exchangeBaseUrlIndex, exchange.baseUrl)
- .toArray();
-
- const availableAmount = Amounts.sub(coin.currentAmount, oldDenom.feeRefresh)
- .amount;
-
- const newCoinDenoms = getWithdrawDenomList(availableAmount, availableDenoms);
-
- if (newCoinDenoms.selectedDenoms.length === 0) {
- logger.trace(
- `not refreshing, available amount ${amountToPretty(
- availableAmount,
- )} too small`,
- );
- await ws.db.runWithWriteTransaction(
- [Stores.coins, Stores.refreshGroups],
- async (tx) => {
- const rg = await tx.get(Stores.refreshGroups, refreshGroupId);
- if (!rg) {
- return;
- }
- rg.finishedPerCoin[coinIndex] = true;
- let allDone = true;
- for (const f of rg.finishedPerCoin) {
- if (!f) {
- allDone = false;
- break;
- }
- }
- if (allDone) {
- rg.timestampFinished = getTimestampNow();
- rg.retryInfo = initRetryInfo(false);
- }
- await tx.put(Stores.refreshGroups, rg);
- },
- );
- ws.notify({ type: NotificationType.RefreshUnwarranted });
- return;
- }
-
- const refreshSession: RefreshSessionRecord = await ws.cryptoApi.createRefreshSession(
- exchange.baseUrl,
- 3,
- coin,
- newCoinDenoms,
- oldDenom.feeRefresh,
- );
-
- // Store refresh session and subtract refreshed amount from
- // coin in the same transaction.
- await ws.db.runWithWriteTransaction(
- [Stores.refreshGroups, Stores.coins],
- async (tx) => {
- const c = await tx.get(Stores.coins, coin.coinPub);
- if (!c) {
- throw Error("coin not found, but marked for refresh");
- }
- const r = Amounts.sub(c.currentAmount, refreshSession.amountRefreshInput);
- if (r.saturated) {
- console.log("can't refresh coin, no amount left");
- return;
- }
- c.currentAmount = r.amount;
- c.status = CoinStatus.Dormant;
- const rg = await tx.get(Stores.refreshGroups, refreshGroupId);
- if (!rg) {
- return;
- }
- if (rg.refreshSessionPerCoin[coinIndex]) {
- return;
- }
- rg.refreshSessionPerCoin[coinIndex] = refreshSession;
- await tx.put(Stores.refreshGroups, rg);
- await tx.put(Stores.coins, c);
- },
- );
- logger.info(
- `created refresh session for coin #${coinIndex} in ${refreshGroupId}`,
- );
- ws.notify({ type: NotificationType.RefreshStarted });
-}
-
-async function refreshMelt(
- ws: InternalWalletState,
- refreshGroupId: string,
- coinIndex: number,
-): Promise<void> {
- const refreshGroup = await ws.db.get(Stores.refreshGroups, refreshGroupId);
- if (!refreshGroup) {
- return;
- }
- const refreshSession = refreshGroup.refreshSessionPerCoin[coinIndex];
- if (!refreshSession) {
- return;
- }
- if (refreshSession.norevealIndex !== undefined) {
- return;
- }
-
- const coin = await ws.db.get(Stores.coins, refreshSession.meltCoinPub);
-
- if (!coin) {
- console.error("can't melt coin, it does not exist");
- return;
- }
-
- const reqUrl = new URL(
- `coins/${coin.coinPub}/melt`,
- refreshSession.exchangeBaseUrl,
- );
- const meltReq = {
- coin_pub: coin.coinPub,
- confirm_sig: refreshSession.confirmSig,
- denom_pub_hash: coin.denomPubHash,
- denom_sig: coin.denomSig,
- rc: refreshSession.hash,
- value_with_fee: Amounts.stringify(refreshSession.amountRefreshInput),
- };
- logger.trace(`melt request for coin:`, meltReq);
- const resp = await ws.http.postJson(reqUrl.href, meltReq);
- const meltResponse = await readSuccessResponseJsonOrThrow(
- resp,
- codecForExchangeMeltResponse(),
- );
-
- const norevealIndex = meltResponse.noreveal_index;
-
- refreshSession.norevealIndex = norevealIndex;
-
- await ws.db.mutate(Stores.refreshGroups, refreshGroupId, (rg) => {
- const rs = rg.refreshSessionPerCoin[coinIndex];
- if (!rs) {
- return;
- }
- if (rs.norevealIndex !== undefined) {
- return;
- }
- if (rs.finishedTimestamp) {
- return;
- }
- rs.norevealIndex = norevealIndex;
- return rg;
- });
-
- ws.notify({
- type: NotificationType.RefreshMelted,
- });
-}
-
-async function refreshReveal(
- ws: InternalWalletState,
- refreshGroupId: string,
- coinIndex: number,
-): Promise<void> {
- const refreshGroup = await ws.db.get(Stores.refreshGroups, refreshGroupId);
- if (!refreshGroup) {
- return;
- }
- const refreshSession = refreshGroup.refreshSessionPerCoin[coinIndex];
- if (!refreshSession) {
- return;
- }
- const norevealIndex = refreshSession.norevealIndex;
- if (norevealIndex === undefined) {
- throw Error("can't reveal without melting first");
- }
- const privs = Array.from(refreshSession.transferPrivs);
- privs.splice(norevealIndex, 1);
-
- const planchets = refreshSession.planchetsForGammas[norevealIndex];
- if (!planchets) {
- throw Error("refresh index error");
- }
-
- const meltCoinRecord = await ws.db.get(
- Stores.coins,
- refreshSession.meltCoinPub,
- );
- if (!meltCoinRecord) {
- throw Error("inconsistent database");
- }
-
- const evs = planchets.map((x: RefreshPlanchetRecord) => x.coinEv);
-
- const linkSigs: string[] = [];
- for (let i = 0; i < refreshSession.newDenoms.length; i++) {
- const linkSig = await ws.cryptoApi.signCoinLink(
- meltCoinRecord.coinPriv,
- refreshSession.newDenomHashes[i],
- refreshSession.meltCoinPub,
- refreshSession.transferPubs[norevealIndex],
- planchets[i].coinEv,
- );
- linkSigs.push(linkSig);
- }
-
- const req = {
- coin_evs: evs,
- new_denoms_h: refreshSession.newDenomHashes,
- rc: refreshSession.hash,
- transfer_privs: privs,
- transfer_pub: refreshSession.transferPubs[norevealIndex],
- link_sigs: linkSigs,
- };
-
- const reqUrl = new URL(
- `refreshes/${refreshSession.hash}/reveal`,
- refreshSession.exchangeBaseUrl,
- );
-
- const resp = await ws.http.postJson(reqUrl.href, req);
- const reveal = await readSuccessResponseJsonOrThrow(
- resp,
- codecForExchangeRevealResponse(),
- );
-
- const coins: CoinRecord[] = [];
-
- for (let i = 0; i < reveal.ev_sigs.length; i++) {
- const denom = await ws.db.get(Stores.denominations, [
- refreshSession.exchangeBaseUrl,
- refreshSession.newDenoms[i],
- ]);
- if (!denom) {
- console.error("denom not found");
- continue;
- }
- const pc = refreshSession.planchetsForGammas[norevealIndex][i];
- const denomSig = await ws.cryptoApi.rsaUnblind(
- reveal.ev_sigs[i].ev_sig,
- pc.blindingKey,
- denom.denomPub,
- );
- const coin: CoinRecord = {
- blindingKey: pc.blindingKey,
- coinPriv: pc.privateKey,
- coinPub: pc.publicKey,
- currentAmount: denom.value,
- denomPub: denom.denomPub,
- denomPubHash: denom.denomPubHash,
- denomSig,
- exchangeBaseUrl: refreshSession.exchangeBaseUrl,
- status: CoinStatus.Fresh,
- coinSource: {
- type: CoinSourceType.Refresh,
- oldCoinPub: refreshSession.meltCoinPub,
- },
- suspended: false,
- };
-
- coins.push(coin);
- }
-
- await ws.db.runWithWriteTransaction(
- [Stores.coins, Stores.refreshGroups],
- async (tx) => {
- const rg = await tx.get(Stores.refreshGroups, refreshGroupId);
- if (!rg) {
- console.log("no refresh session found");
- return;
- }
- const rs = rg.refreshSessionPerCoin[coinIndex];
- if (!rs) {
- return;
- }
- if (rs.finishedTimestamp) {
- console.log("refresh session already finished");
- return;
- }
- rs.finishedTimestamp = getTimestampNow();
- rg.finishedPerCoin[coinIndex] = true;
- let allDone = true;
- for (const f of rg.finishedPerCoin) {
- if (!f) {
- allDone = false;
- break;
- }
- }
- if (allDone) {
- rg.timestampFinished = getTimestampNow();
- rg.retryInfo = initRetryInfo(false);
- }
- for (const coin of coins) {
- await tx.put(Stores.coins, coin);
- }
- await tx.put(Stores.refreshGroups, rg);
- },
- );
- console.log("refresh finished (end of reveal)");
- ws.notify({
- type: NotificationType.RefreshRevealed,
- });
-}
-
-async function incrementRefreshRetry(
- ws: InternalWalletState,
- refreshGroupId: string,
- err: OperationErrorDetails | undefined,
-): Promise<void> {
- await ws.db.runWithWriteTransaction([Stores.refreshGroups], async (tx) => {
- const r = await tx.get(Stores.refreshGroups, refreshGroupId);
- if (!r) {
- return;
- }
- if (!r.retryInfo) {
- return;
- }
- r.retryInfo.retryCounter++;
- updateRetryInfoTimeout(r.retryInfo);
- r.lastError = err;
- await tx.put(Stores.refreshGroups, r);
- });
- if (err) {
- ws.notify({ type: NotificationType.RefreshOperationError, error: err });
- }
-}
-
-export async function processRefreshGroup(
- ws: InternalWalletState,
- refreshGroupId: string,
- forceNow = false,
-): Promise<void> {
- await ws.memoProcessRefresh.memo(refreshGroupId, async () => {
- const onOpErr = (e: OperationErrorDetails): Promise<void> =>
- incrementRefreshRetry(ws, refreshGroupId, e);
- return await guardOperationException(
- async () => await processRefreshGroupImpl(ws, refreshGroupId, forceNow),
- onOpErr,
- );
- });
-}
-
-async function resetRefreshGroupRetry(
- ws: InternalWalletState,
- refreshSessionId: string,
-): Promise<void> {
- await ws.db.mutate(Stores.refreshGroups, refreshSessionId, (x) => {
- if (x.retryInfo.active) {
- x.retryInfo = initRetryInfo();
- }
- return x;
- });
-}
-
-async function processRefreshGroupImpl(
- ws: InternalWalletState,
- refreshGroupId: string,
- forceNow: boolean,
-): Promise<void> {
- if (forceNow) {
- await resetRefreshGroupRetry(ws, refreshGroupId);
- }
- const refreshGroup = await ws.db.get(Stores.refreshGroups, refreshGroupId);
- if (!refreshGroup) {
- return;
- }
- if (refreshGroup.timestampFinished) {
- return;
- }
- const ps = refreshGroup.oldCoinPubs.map((x, i) =>
- processRefreshSession(ws, refreshGroupId, i),
- );
- await Promise.all(ps);
- logger.trace("refresh finished");
-}
-
-async function processRefreshSession(
- ws: InternalWalletState,
- refreshGroupId: string,
- coinIndex: number,
-): Promise<void> {
- logger.trace(
- `processing refresh session for coin ${coinIndex} of group ${refreshGroupId}`,
- );
- let refreshGroup = await ws.db.get(Stores.refreshGroups, refreshGroupId);
- if (!refreshGroup) {
- return;
- }
- if (refreshGroup.finishedPerCoin[coinIndex]) {
- return;
- }
- if (!refreshGroup.refreshSessionPerCoin[coinIndex]) {
- await refreshCreateSession(ws, refreshGroupId, coinIndex);
- refreshGroup = await ws.db.get(Stores.refreshGroups, refreshGroupId);
- if (!refreshGroup) {
- return;
- }
- }
- const refreshSession = refreshGroup.refreshSessionPerCoin[coinIndex];
- if (!refreshSession) {
- if (!refreshGroup.finishedPerCoin[coinIndex]) {
- throw Error(
- "BUG: refresh session was not created and coin not marked as finished",
- );
- }
- return;
- }
- if (refreshSession.norevealIndex === undefined) {
- await refreshMelt(ws, refreshGroupId, coinIndex);
- }
- await refreshReveal(ws, refreshGroupId, coinIndex);
-}
-
-/**
- * Create a refresh group for a list of coins.
- */
-export async function createRefreshGroup(
- ws: InternalWalletState,
- tx: TransactionHandle,
- oldCoinPubs: CoinPublicKey[],
- reason: RefreshReason,
-): Promise<RefreshGroupId> {
- const refreshGroupId = encodeCrock(getRandomBytes(32));
-
- const refreshGroup: RefreshGroupRecord = {
- timestampFinished: undefined,
- finishedPerCoin: oldCoinPubs.map((x) => false),
- lastError: undefined,
- lastErrorPerCoin: {},
- oldCoinPubs: oldCoinPubs.map((x) => x.coinPub),
- reason,
- refreshGroupId,
- refreshSessionPerCoin: oldCoinPubs.map((x) => undefined),
- retryInfo: initRetryInfo(),
- };
-
- await tx.put(Stores.refreshGroups, refreshGroup);
-
- const processAsync = async (): Promise<void> => {
- try {
- await processRefreshGroup(ws, refreshGroupId);
- } catch (e) {
- logger.trace(`Error during refresh: ${e}`)
- }
- };
-
- processAsync();
-
- return {
- refreshGroupId,
- };
-}
diff --git a/src/operations/refund.ts b/src/operations/refund.ts
deleted file mode 100644
index 35384c087..000000000
--- a/src/operations/refund.ts
+++ /dev/null
@@ -1,425 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2019-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/>
- */
-
-/**
- * Implementation of the refund operation.
- *
- * @author Florian Dold
- */
-
-/**
- * Imports.
- */
-import { InternalWalletState } from "./state";
-import {
- OperationErrorDetails,
- RefreshReason,
- CoinPublicKey,
-} from "../types/walletTypes";
-import {
- Stores,
- updateRetryInfoTimeout,
- initRetryInfo,
- CoinStatus,
- RefundReason,
- RefundState,
- PurchaseRecord,
-} from "../types/dbTypes";
-import { NotificationType } from "../types/notifications";
-import { parseRefundUri } from "../util/taleruri";
-import { createRefreshGroup, getTotalRefreshCost } from "./refresh";
-import { Amounts } from "../util/amounts";
-import {
- MerchantCoinRefundStatus,
- MerchantCoinRefundSuccessStatus,
- MerchantCoinRefundFailureStatus,
- codecForMerchantOrderStatusPaid,
-} from "../types/talerTypes";
-import { guardOperationException } from "./errors";
-import { getTimestampNow } from "../util/time";
-import { Logger } from "../util/logging";
-import { readSuccessResponseJsonOrThrow } from "../util/http";
-import { TransactionHandle } from "../util/query";
-
-const logger = new Logger("refund.ts");
-
-/**
- * Retry querying and applying refunds for an order later.
- */
-async function incrementPurchaseQueryRefundRetry(
- ws: InternalWalletState,
- proposalId: string,
- err: OperationErrorDetails | undefined,
-): Promise<void> {
- await ws.db.runWithWriteTransaction([Stores.purchases], async (tx) => {
- const pr = await tx.get(Stores.purchases, proposalId);
- if (!pr) {
- return;
- }
- if (!pr.refundStatusRetryInfo) {
- return;
- }
- pr.refundStatusRetryInfo.retryCounter++;
- updateRetryInfoTimeout(pr.refundStatusRetryInfo);
- pr.lastRefundStatusError = err;
- await tx.put(Stores.purchases, pr);
- });
- if (err) {
- ws.notify({
- type: NotificationType.RefundStatusOperationError,
- error: err,
- });
- }
-}
-
-function getRefundKey(d: MerchantCoinRefundStatus): string {
- return `${d.coin_pub}-${d.rtransaction_id}`;
-}
-
-async function applySuccessfulRefund(
- tx: TransactionHandle,
- p: PurchaseRecord,
- refreshCoinsMap: Record<string, { coinPub: string }>,
- r: MerchantCoinRefundSuccessStatus,
-): Promise<void> {
- // FIXME: check signature before storing it as valid!
-
- const refundKey = getRefundKey(r);
- const coin = await tx.get(Stores.coins, r.coin_pub);
- if (!coin) {
- console.warn("coin not found, can't apply refund");
- return;
- }
- const denom = await tx.getIndexed(
- Stores.denominations.denomPubHashIndex,
- coin.denomPubHash,
- );
- if (!denom) {
- throw Error("inconsistent database");
- }
- refreshCoinsMap[coin.coinPub] = { coinPub: coin.coinPub };
- const refundAmount = Amounts.parseOrThrow(r.refund_amount);
- const refundFee = denom.feeRefund;
- coin.status = CoinStatus.Dormant;
- coin.currentAmount = Amounts.add(coin.currentAmount, refundAmount).amount;
- coin.currentAmount = Amounts.sub(coin.currentAmount, refundFee).amount;
- logger.trace(`coin amount after is ${Amounts.stringify(coin.currentAmount)}`);
- await tx.put(Stores.coins, coin);
-
- const allDenoms = await tx
- .iterIndexed(Stores.denominations.exchangeBaseUrlIndex, coin.exchangeBaseUrl)
- .toArray();
-
- const amountLeft = Amounts.sub(
- Amounts.add(coin.currentAmount, Amounts.parseOrThrow(r.refund_amount))
- .amount,
- denom.feeRefund,
- ).amount;
-
- const totalRefreshCostBound = getTotalRefreshCost(
- allDenoms,
- denom,
- amountLeft,
- );
-
- p.refunds[refundKey] = {
- type: RefundState.Applied,
- executionTime: r.execution_time,
- refundAmount: Amounts.parseOrThrow(r.refund_amount),
- refundFee: denom.feeRefund,
- totalRefreshCostBound,
- };
-}
-
-async function storePendingRefund(
- tx: TransactionHandle,
- p: PurchaseRecord,
- r: MerchantCoinRefundFailureStatus,
-): Promise<void> {
- const refundKey = getRefundKey(r);
-
- const coin = await tx.get(Stores.coins, r.coin_pub);
- if (!coin) {
- console.warn("coin not found, can't apply refund");
- return;
- }
- const denom = await tx.getIndexed(
- Stores.denominations.denomPubHashIndex,
- coin.denomPubHash,
- );
-
- if (!denom) {
- throw Error("inconsistent database");
- }
-
- const allDenoms = await tx
- .iterIndexed(Stores.denominations.exchangeBaseUrlIndex, coin.exchangeBaseUrl)
- .toArray();
-
- const amountLeft = Amounts.sub(
- Amounts.add(coin.currentAmount, Amounts.parseOrThrow(r.refund_amount))
- .amount,
- denom.feeRefund,
- ).amount;
-
- const totalRefreshCostBound = getTotalRefreshCost(
- allDenoms,
- denom,
- amountLeft,
- );
-
- p.refunds[refundKey] = {
- type: RefundState.Pending,
- executionTime: r.execution_time,
- refundAmount: Amounts.parseOrThrow(r.refund_amount),
- refundFee: denom.feeRefund,
- totalRefreshCostBound,
- };
-}
-
-async function acceptRefunds(
- ws: InternalWalletState,
- proposalId: string,
- refunds: MerchantCoinRefundStatus[],
- reason: RefundReason,
-): Promise<void> {
- console.log("handling refunds", refunds);
- const now = getTimestampNow();
-
- await ws.db.runWithWriteTransaction(
- [Stores.purchases, Stores.coins, Stores.denominations, Stores.refreshGroups, Stores.refundEvents],
- async (tx) => {
- const p = await tx.get(Stores.purchases, proposalId);
- if (!p) {
- console.error("purchase not found, not adding refunds");
- return;
- }
-
- const refreshCoinsMap: Record<string, CoinPublicKey> = {};
-
- for (const refundStatus of refunds) {
- const refundKey = getRefundKey(refundStatus);
- const existingRefundInfo = p.refunds[refundKey];
-
- // Already failed.
- if (existingRefundInfo?.type === RefundState.Failed) {
- continue;
- }
-
- // Already applied.
- if (existingRefundInfo?.type === RefundState.Applied) {
- continue;
- }
-
- // Still pending.
- if (
- refundStatus.type === "failure" &&
- existingRefundInfo?.type === RefundState.Pending
- ) {
- continue;
- }
-
- // Invariant: (!existingRefundInfo) || (existingRefundInfo === Pending)
-
- if (refundStatus.type === "success") {
- await applySuccessfulRefund(tx, p, refreshCoinsMap, refundStatus);
- } else {
- await storePendingRefund(tx, p, refundStatus);
- }
- }
-
- const refreshCoinsPubs = Object.values(refreshCoinsMap);
- await createRefreshGroup(ws, tx, refreshCoinsPubs, RefreshReason.Refund);
-
- // Are we done with querying yet, or do we need to do another round
- // after a retry delay?
- let queryDone = true;
-
- if (p.autoRefundDeadline && p.autoRefundDeadline.t_ms > now.t_ms) {
- queryDone = false;
- }
-
- let numPendingRefunds = 0;
- for (const ri of Object.values(p.refunds)) {
- switch (ri.type) {
- case RefundState.Pending:
- numPendingRefunds++;
- break;
- }
- }
-
- if (numPendingRefunds > 0) {
- queryDone = false;
- }
-
- if (queryDone) {
- p.timestampLastRefundStatus = now;
- p.lastRefundStatusError = undefined;
- p.refundStatusRetryInfo = initRetryInfo(false);
- p.refundStatusRequested = false;
- logger.trace("refund query done");
- } else {
- // No error, but we need to try again!
- p.timestampLastRefundStatus = now;
- p.refundStatusRetryInfo.retryCounter++;
- updateRetryInfoTimeout(p.refundStatusRetryInfo);
- p.lastRefundStatusError = undefined;
- logger.trace("refund query not done");
- }
-
- await tx.put(Stores.purchases, p);
- },
- );
-
- ws.notify({
- type: NotificationType.RefundQueried,
- });
-}
-
-async function startRefundQuery(
- ws: InternalWalletState,
- proposalId: string,
-): Promise<void> {
- const success = await ws.db.runWithWriteTransaction(
- [Stores.purchases],
- async (tx) => {
- const p = await tx.get(Stores.purchases, proposalId);
- if (!p) {
- logger.error("no purchase found for refund URL");
- return false;
- }
- p.refundStatusRequested = true;
- p.lastRefundStatusError = undefined;
- p.refundStatusRetryInfo = initRetryInfo();
- await tx.put(Stores.purchases, p);
- return true;
- },
- );
-
- if (!success) {
- return;
- }
-
- ws.notify({
- type: NotificationType.RefundStarted,
- });
-
- await processPurchaseQueryRefund(ws, proposalId);
-}
-
-/**
- * Accept a refund, return the contract hash for the contract
- * that was involved in the refund.
- */
-export async function applyRefund(
- ws: InternalWalletState,
- talerRefundUri: string,
-): Promise<{ contractTermsHash: string; proposalId: string }> {
- const parseResult = parseRefundUri(talerRefundUri);
-
- logger.trace("applying refund", parseResult);
-
- if (!parseResult) {
- throw Error("invalid refund URI");
- }
-
- const purchase = await ws.db.getIndexed(Stores.purchases.orderIdIndex, [
- parseResult.merchantBaseUrl,
- parseResult.orderId,
- ]);
-
- if (!purchase) {
- throw Error(
- `no purchase for the taler://refund/ URI (${talerRefundUri}) was found`,
- );
- }
-
- logger.info("processing purchase for refund");
- await startRefundQuery(ws, purchase.proposalId);
-
- return {
- contractTermsHash: purchase.contractData.contractTermsHash,
- proposalId: purchase.proposalId,
- };
-}
-
-export async function processPurchaseQueryRefund(
- ws: InternalWalletState,
- proposalId: string,
- forceNow = false,
-): Promise<void> {
- const onOpErr = (e: OperationErrorDetails): Promise<void> =>
- incrementPurchaseQueryRefundRetry(ws, proposalId, e);
- await guardOperationException(
- () => processPurchaseQueryRefundImpl(ws, proposalId, forceNow),
- onOpErr,
- );
-}
-
-async function resetPurchaseQueryRefundRetry(
- ws: InternalWalletState,
- proposalId: string,
-): Promise<void> {
- await ws.db.mutate(Stores.purchases, proposalId, (x) => {
- if (x.refundStatusRetryInfo.active) {
- x.refundStatusRetryInfo = initRetryInfo();
- }
- return x;
- });
-}
-
-async function processPurchaseQueryRefundImpl(
- ws: InternalWalletState,
- proposalId: string,
- forceNow: boolean,
-): Promise<void> {
- if (forceNow) {
- await resetPurchaseQueryRefundRetry(ws, proposalId);
- }
- const purchase = await ws.db.get(Stores.purchases, proposalId);
- if (!purchase) {
- return;
- }
-
- if (!purchase.refundStatusRequested) {
- return;
- }
-
- const requestUrl = new URL(
- `orders/${purchase.contractData.orderId}`,
- purchase.contractData.merchantBaseUrl,
- );
- requestUrl.searchParams.set(
- "h_contract",
- purchase.contractData.contractTermsHash,
- );
-
- const request = await ws.http.get(requestUrl.href);
-
- console.log("got json", JSON.stringify(await request.json(), undefined, 2));
-
- const refundResponse = await readSuccessResponseJsonOrThrow(
- request,
- codecForMerchantOrderStatusPaid(),
- );
-
- await acceptRefunds(
- ws,
- proposalId,
- refundResponse.refunds,
- RefundReason.NormalRefund,
- );
-}
diff --git a/src/operations/reserves.ts b/src/operations/reserves.ts
deleted file mode 100644
index 405a02f9e..000000000
--- a/src/operations/reserves.ts
+++ /dev/null
@@ -1,840 +0,0 @@
-/*
- 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 {
- CreateReserveRequest,
- CreateReserveResponse,
- OperationErrorDetails,
- AcceptWithdrawalResponse,
-} from "../types/walletTypes";
-import { canonicalizeBaseUrl } from "../util/helpers";
-import { InternalWalletState } from "./state";
-import {
- ReserveRecordStatus,
- ReserveRecord,
- CurrencyRecord,
- Stores,
- WithdrawalGroupRecord,
- initRetryInfo,
- updateRetryInfoTimeout,
- ReserveUpdatedEventRecord,
- WalletReserveHistoryItemType,
- WithdrawalSourceType,
- ReserveHistoryRecord,
- ReserveBankInfo,
-} from "../types/dbTypes";
-import { Logger } from "../util/logging";
-import { Amounts } from "../util/amounts";
-import {
- updateExchangeFromUrl,
- getExchangeTrust,
- getExchangePaytoUri,
-} from "./exchanges";
-import {
- codecForWithdrawOperationStatusResponse,
- codecForBankWithdrawalOperationPostResponse,
-} from "../types/talerTypes";
-import { assertUnreachable } from "../util/assertUnreachable";
-import { encodeCrock, getRandomBytes } from "../crypto/talerCrypto";
-import { randomBytes } from "../crypto/primitives/nacl-fast";
-import {
- selectWithdrawalDenoms,
- processWithdrawGroup,
- getBankWithdrawalInfo,
- denomSelectionInfoToState,
-} from "./withdraw";
-import {
- guardOperationException,
- OperationFailedAndReportedError,
- makeErrorDetails,
-} from "./errors";
-import { NotificationType } from "../types/notifications";
-import { codecForReserveStatus } from "../types/ReserveStatus";
-import { getTimestampNow } from "../util/time";
-import {
- reconcileReserveHistory,
- summarizeReserveHistory,
-} from "../util/reserveHistoryUtil";
-import { TransactionHandle } from "../util/query";
-import { addPaytoQueryParams } from "../util/payto";
-import { TalerErrorCode } from "../TalerErrorCode";
-import {
- readSuccessResponseJsonOrErrorCode,
- throwUnexpectedRequestError,
- readSuccessResponseJsonOrThrow,
-} from "../util/http";
-import { codecForAny } from "../util/codec";
-
-const logger = new Logger("reserves.ts");
-
-async function resetReserveRetry(
- ws: InternalWalletState,
- reservePub: string,
-): Promise<void> {
- await ws.db.mutate(Stores.reserves, reservePub, (x) => {
- if (x.retryInfo.active) {
- x.retryInfo = initRetryInfo();
- }
- return x;
- });
-}
-
-/**
- * Create a reserve, but do not flag it as confirmed yet.
- *
- * Adds the corresponding exchange as a trusted exchange if it is neither
- * audited nor trusted already.
- */
-export async function createReserve(
- ws: InternalWalletState,
- req: CreateReserveRequest,
-): Promise<CreateReserveResponse> {
- const keypair = await ws.cryptoApi.createEddsaKeypair();
- const now = getTimestampNow();
- const canonExchange = canonicalizeBaseUrl(req.exchange);
-
- let reserveStatus;
- if (req.bankWithdrawStatusUrl) {
- reserveStatus = ReserveRecordStatus.REGISTERING_BANK;
- } else {
- reserveStatus = ReserveRecordStatus.QUERYING_STATUS;
- }
-
- let bankInfo: ReserveBankInfo | undefined;
-
- if (req.bankWithdrawStatusUrl) {
- if (!req.exchangePaytoUri) {
- throw Error(
- "Exchange payto URI must be specified for a bank-integrated withdrawal",
- );
- }
- bankInfo = {
- statusUrl: req.bankWithdrawStatusUrl,
- exchangePaytoUri: req.exchangePaytoUri,
- };
- }
-
- const initialWithdrawalGroupId = encodeCrock(getRandomBytes(32));
-
- const denomSelInfo = await selectWithdrawalDenoms(
- ws,
- canonExchange,
- req.amount,
- );
- const initialDenomSel = denomSelectionInfoToState(denomSelInfo);
-
- const reserveRecord: ReserveRecord = {
- instructedAmount: req.amount,
- initialWithdrawalGroupId,
- initialDenomSel,
- initialWithdrawalStarted: false,
- timestampCreated: now,
- exchangeBaseUrl: canonExchange,
- reservePriv: keypair.priv,
- reservePub: keypair.pub,
- senderWire: req.senderWire,
- timestampBankConfirmed: undefined,
- timestampReserveInfoPosted: undefined,
- bankInfo,
- reserveStatus,
- lastSuccessfulStatusQuery: undefined,
- retryInfo: initRetryInfo(),
- lastError: undefined,
- currency: req.amount.currency,
- };
-
- const reserveHistoryRecord: ReserveHistoryRecord = {
- reservePub: keypair.pub,
- reserveTransactions: [],
- };
-
- reserveHistoryRecord.reserveTransactions.push({
- type: WalletReserveHistoryItemType.Credit,
- expectedAmount: req.amount,
- });
-
- const senderWire = req.senderWire;
- if (senderWire) {
- const rec = {
- paytoUri: senderWire,
- };
- await ws.db.put(Stores.senderWires, rec);
- }
-
- const exchangeInfo = await updateExchangeFromUrl(ws, req.exchange);
- const exchangeDetails = exchangeInfo.details;
- if (!exchangeDetails) {
- console.log(exchangeDetails);
- throw Error("exchange not updated");
- }
- const { isAudited, isTrusted } = await getExchangeTrust(ws, exchangeInfo);
- let currencyRecord = await ws.db.get(
- Stores.currencies,
- exchangeDetails.currency,
- );
- if (!currencyRecord) {
- currencyRecord = {
- auditors: [],
- exchanges: [],
- fractionalDigits: 2,
- name: exchangeDetails.currency,
- };
- }
-
- if (!isAudited && !isTrusted) {
- currencyRecord.exchanges.push({
- baseUrl: req.exchange,
- exchangePub: exchangeDetails.masterPublicKey,
- });
- }
-
- const cr: CurrencyRecord = currencyRecord;
-
- const resp = await ws.db.runWithWriteTransaction(
- [
- Stores.currencies,
- Stores.reserves,
- Stores.reserveHistory,
- Stores.bankWithdrawUris,
- ],
- async (tx) => {
- // Check if we have already created a reserve for that bankWithdrawStatusUrl
- if (reserveRecord.bankInfo?.statusUrl) {
- const bwi = await tx.get(
- Stores.bankWithdrawUris,
- reserveRecord.bankInfo.statusUrl,
- );
- if (bwi) {
- const otherReserve = await tx.get(Stores.reserves, bwi.reservePub);
- if (otherReserve) {
- logger.trace(
- "returning existing reserve for bankWithdrawStatusUri",
- );
- return {
- exchange: otherReserve.exchangeBaseUrl,
- reservePub: otherReserve.reservePub,
- };
- }
- }
- await tx.put(Stores.bankWithdrawUris, {
- reservePub: reserveRecord.reservePub,
- talerWithdrawUri: reserveRecord.bankInfo.statusUrl,
- });
- }
- await tx.put(Stores.currencies, cr);
- await tx.put(Stores.reserves, reserveRecord);
- await tx.put(Stores.reserveHistory, reserveHistoryRecord);
- const r: CreateReserveResponse = {
- exchange: canonExchange,
- reservePub: keypair.pub,
- };
- return r;
- },
- );
-
- if (reserveRecord.reservePub === resp.reservePub) {
- // Only emit notification when a new reserve was created.
- ws.notify({
- type: NotificationType.ReserveCreated,
- reservePub: reserveRecord.reservePub,
- });
- }
-
- // Asynchronously process the reserve, but return
- // to the caller already.
- processReserve(ws, resp.reservePub, true).catch((e) => {
- logger.error("Processing reserve (after createReserve) failed:", e);
- });
-
- return resp;
-}
-
-/**
- * Re-query the status of a reserve.
- */
-export async function forceQueryReserve(
- ws: InternalWalletState,
- reservePub: string,
-): Promise<void> {
- await ws.db.runWithWriteTransaction([Stores.reserves], async (tx) => {
- const reserve = await tx.get(Stores.reserves, reservePub);
- if (!reserve) {
- return;
- }
- // Only force status query where it makes sense
- switch (reserve.reserveStatus) {
- case ReserveRecordStatus.DORMANT:
- case ReserveRecordStatus.WITHDRAWING:
- case ReserveRecordStatus.QUERYING_STATUS:
- break;
- default:
- return;
- }
- reserve.reserveStatus = ReserveRecordStatus.QUERYING_STATUS;
- reserve.retryInfo = initRetryInfo();
- await tx.put(Stores.reserves, reserve);
- });
- await processReserve(ws, reservePub, true);
-}
-
-/**
- * First fetch information requred to withdraw from the reserve,
- * then deplete the reserve, withdrawing coins until it is empty.
- *
- * The returned promise resolves once the reserve is set to the
- * state DORMANT.
- */
-export async function processReserve(
- ws: InternalWalletState,
- reservePub: string,
- forceNow = false,
-): Promise<void> {
- return ws.memoProcessReserve.memo(reservePub, async () => {
- const onOpError = (err: OperationErrorDetails): Promise<void> =>
- incrementReserveRetry(ws, reservePub, err);
- await guardOperationException(
- () => processReserveImpl(ws, reservePub, forceNow),
- onOpError,
- );
- });
-}
-
-async function registerReserveWithBank(
- ws: InternalWalletState,
- reservePub: string,
-): Promise<void> {
- const reserve = await ws.db.get(Stores.reserves, reservePub);
- switch (reserve?.reserveStatus) {
- case ReserveRecordStatus.WAIT_CONFIRM_BANK:
- case ReserveRecordStatus.REGISTERING_BANK:
- break;
- default:
- return;
- }
- const bankInfo = reserve.bankInfo;
- if (!bankInfo) {
- return;
- }
- const bankStatusUrl = bankInfo.statusUrl;
- const httpResp = await ws.http.postJson(bankStatusUrl, {
- reserve_pub: reservePub,
- selected_exchange: bankInfo.exchangePaytoUri,
- });
- await readSuccessResponseJsonOrThrow(
- httpResp,
- codecForBankWithdrawalOperationPostResponse(),
- );
- await ws.db.mutate(Stores.reserves, reservePub, (r) => {
- switch (r.reserveStatus) {
- case ReserveRecordStatus.REGISTERING_BANK:
- case ReserveRecordStatus.WAIT_CONFIRM_BANK:
- break;
- default:
- return;
- }
- r.timestampReserveInfoPosted = getTimestampNow();
- r.reserveStatus = ReserveRecordStatus.WAIT_CONFIRM_BANK;
- if (!r.bankInfo) {
- throw Error("invariant failed");
- }
- r.retryInfo = initRetryInfo();
- return r;
- });
- ws.notify({ type: NotificationType.ReserveRegisteredWithBank });
- return processReserveBankStatus(ws, reservePub);
-}
-
-export async function processReserveBankStatus(
- ws: InternalWalletState,
- reservePub: string,
-): Promise<void> {
- const onOpError = (err: OperationErrorDetails): Promise<void> =>
- incrementReserveRetry(ws, reservePub, err);
- await guardOperationException(
- () => processReserveBankStatusImpl(ws, reservePub),
- onOpError,
- );
-}
-
-async function processReserveBankStatusImpl(
- ws: InternalWalletState,
- reservePub: string,
-): Promise<void> {
- const reserve = await ws.db.get(Stores.reserves, reservePub);
- switch (reserve?.reserveStatus) {
- case ReserveRecordStatus.WAIT_CONFIRM_BANK:
- case ReserveRecordStatus.REGISTERING_BANK:
- break;
- default:
- return;
- }
- const bankStatusUrl = reserve.bankInfo?.statusUrl;
- if (!bankStatusUrl) {
- return;
- }
-
- const statusResp = await ws.http.get(bankStatusUrl);
- const status = await readSuccessResponseJsonOrThrow(
- statusResp,
- codecForWithdrawOperationStatusResponse(),
- );
-
- if (status.selection_done) {
- if (reserve.reserveStatus === ReserveRecordStatus.REGISTERING_BANK) {
- await registerReserveWithBank(ws, reservePub);
- return await processReserveBankStatus(ws, reservePub);
- }
- } else {
- await registerReserveWithBank(ws, reservePub);
- return await processReserveBankStatus(ws, reservePub);
- }
-
- if (status.transfer_done) {
- await ws.db.mutate(Stores.reserves, reservePub, (r) => {
- switch (r.reserveStatus) {
- case ReserveRecordStatus.REGISTERING_BANK:
- case ReserveRecordStatus.WAIT_CONFIRM_BANK:
- break;
- default:
- return;
- }
- const now = getTimestampNow();
- r.timestampBankConfirmed = now;
- r.reserveStatus = ReserveRecordStatus.QUERYING_STATUS;
- r.retryInfo = initRetryInfo();
- return r;
- });
- await processReserveImpl(ws, reservePub, true);
- } else {
- await ws.db.mutate(Stores.reserves, reservePub, (r) => {
- switch (r.reserveStatus) {
- case ReserveRecordStatus.WAIT_CONFIRM_BANK:
- break;
- default:
- return;
- }
- if (r.bankInfo) {
- r.bankInfo.confirmUrl = status.confirm_transfer_url;
- }
- return r;
- });
- await incrementReserveRetry(ws, reservePub, undefined);
- }
-}
-
-async function incrementReserveRetry(
- ws: InternalWalletState,
- reservePub: string,
- err: OperationErrorDetails | undefined,
-): Promise<void> {
- await ws.db.runWithWriteTransaction([Stores.reserves], async (tx) => {
- const r = await tx.get(Stores.reserves, reservePub);
- if (!r) {
- return;
- }
- if (!r.retryInfo) {
- return;
- }
- r.retryInfo.retryCounter++;
- updateRetryInfoTimeout(r.retryInfo);
- r.lastError = err;
- await tx.put(Stores.reserves, r);
- });
- if (err) {
- ws.notify({
- type: NotificationType.ReserveOperationError,
- error: err,
- });
- }
-}
-
-/**
- * Update the information about a reserve that is stored in the wallet
- * by quering the reserve's exchange.
- */
-async function updateReserve(
- ws: InternalWalletState,
- reservePub: string,
-): Promise<{ ready: boolean }> {
- const reserve = await ws.db.get(Stores.reserves, reservePub);
- if (!reserve) {
- throw Error("reserve not in db");
- }
-
- if (reserve.reserveStatus !== ReserveRecordStatus.QUERYING_STATUS) {
- return { ready: true };
- }
-
- const resp = await ws.http.get(
- new URL(`reserves/${reservePub}`, reserve.exchangeBaseUrl).href,
- );
-
- const result = await readSuccessResponseJsonOrErrorCode(
- resp,
- codecForReserveStatus(),
- );
- if (result.isError) {
- if (
- resp.status === 404 &&
- result.talerErrorResponse.code === TalerErrorCode.RESERVE_STATUS_UNKNOWN
- ) {
- ws.notify({
- type: NotificationType.ReserveNotYetFound,
- reservePub,
- });
- await incrementReserveRetry(ws, reservePub, undefined);
- return { ready: false };
- } else {
- throwUnexpectedRequestError(resp, result.talerErrorResponse);
- }
- }
-
- const reserveInfo = result.response;
-
- const balance = Amounts.parseOrThrow(reserveInfo.balance);
- const currency = balance.currency;
- await ws.db.runWithWriteTransaction(
- [Stores.reserves, Stores.reserveUpdatedEvents, Stores.reserveHistory],
- async (tx) => {
- const r = await tx.get(Stores.reserves, reservePub);
- if (!r) {
- return;
- }
- if (r.reserveStatus !== ReserveRecordStatus.QUERYING_STATUS) {
- return;
- }
-
- const hist = await tx.get(Stores.reserveHistory, reservePub);
- if (!hist) {
- throw Error("inconsistent database");
- }
-
- const newHistoryTransactions = reserveInfo.history.slice(
- hist.reserveTransactions.length,
- );
-
- const reserveUpdateId = encodeCrock(getRandomBytes(32));
-
- const reconciled = reconcileReserveHistory(
- hist.reserveTransactions,
- reserveInfo.history,
- );
-
- const summary = summarizeReserveHistory(
- reconciled.updatedLocalHistory,
- currency,
- );
-
- if (
- reconciled.newAddedItems.length + reconciled.newMatchedItems.length !=
- 0
- ) {
- const reserveUpdate: ReserveUpdatedEventRecord = {
- reservePub: r.reservePub,
- timestamp: getTimestampNow(),
- amountReserveBalance: Amounts.stringify(balance),
- amountExpected: Amounts.stringify(summary.awaitedReserveAmount),
- newHistoryTransactions,
- reserveUpdateId,
- };
- await tx.put(Stores.reserveUpdatedEvents, reserveUpdate);
- r.reserveStatus = ReserveRecordStatus.WITHDRAWING;
- r.retryInfo = initRetryInfo();
- } else {
- r.reserveStatus = ReserveRecordStatus.DORMANT;
- r.retryInfo = initRetryInfo(false);
- }
- r.lastSuccessfulStatusQuery = getTimestampNow();
- hist.reserveTransactions = reconciled.updatedLocalHistory;
- r.lastError = undefined;
- await tx.put(Stores.reserves, r);
- await tx.put(Stores.reserveHistory, hist);
- },
- );
- ws.notify({ type: NotificationType.ReserveUpdated });
- return { ready: true };
-}
-
-async function processReserveImpl(
- ws: InternalWalletState,
- reservePub: string,
- forceNow = false,
-): Promise<void> {
- const reserve = await ws.db.get(Stores.reserves, reservePub);
- if (!reserve) {
- console.log("not processing reserve: reserve does not exist");
- return;
- }
- if (!forceNow) {
- const now = getTimestampNow();
- if (reserve.retryInfo.nextRetry.t_ms > now.t_ms) {
- logger.trace("processReserve retry not due yet");
- return;
- }
- } else {
- await resetReserveRetry(ws, reservePub);
- }
- logger.trace(
- `Processing reserve ${reservePub} with status ${reserve.reserveStatus}`,
- );
- switch (reserve.reserveStatus) {
- case ReserveRecordStatus.REGISTERING_BANK:
- await processReserveBankStatus(ws, reservePub);
- return await processReserveImpl(ws, reservePub, true);
- case ReserveRecordStatus.QUERYING_STATUS: {
- const res = await updateReserve(ws, reservePub);
- if (res.ready) {
- return await processReserveImpl(ws, reservePub, true);
- } else {
- break;
- }
- }
- case ReserveRecordStatus.WITHDRAWING:
- await depleteReserve(ws, reservePub);
- break;
- case ReserveRecordStatus.DORMANT:
- // nothing to do
- break;
- case ReserveRecordStatus.WAIT_CONFIRM_BANK:
- await processReserveBankStatus(ws, reservePub);
- break;
- default:
- console.warn("unknown reserve record status:", reserve.reserveStatus);
- assertUnreachable(reserve.reserveStatus);
- break;
- }
-}
-
-/**
- * Withdraw coins from a reserve until it is empty.
- *
- * When finished, marks the reserve as depleted by setting
- * the depleted timestamp.
- */
-async function depleteReserve(
- ws: InternalWalletState,
- reservePub: string,
-): Promise<void> {
- let reserve: ReserveRecord | undefined;
- let hist: ReserveHistoryRecord | undefined;
- await ws.db.runWithReadTransaction(
- [Stores.reserves, Stores.reserveHistory],
- async (tx) => {
- reserve = await tx.get(Stores.reserves, reservePub);
- hist = await tx.get(Stores.reserveHistory, reservePub);
- },
- );
-
- if (!reserve) {
- return;
- }
- if (!hist) {
- throw Error("inconsistent database");
- }
- if (reserve.reserveStatus !== ReserveRecordStatus.WITHDRAWING) {
- return;
- }
- logger.trace(`depleting reserve ${reservePub}`);
-
- const summary = summarizeReserveHistory(
- hist.reserveTransactions,
- reserve.currency,
- );
-
- const withdrawAmount = summary.unclaimedReserveAmount;
-
- const denomsForWithdraw = await selectWithdrawalDenoms(
- ws,
- reserve.exchangeBaseUrl,
- withdrawAmount,
- );
- if (!denomsForWithdraw) {
- // Only complain about inability to withdraw if we
- // didn't withdraw before.
- if (Amounts.isZero(summary.withdrawnAmount)) {
- const opErr = makeErrorDetails(
- TalerErrorCode.WALLET_EXCHANGE_DENOMINATIONS_INSUFFICIENT,
- `Unable to withdraw from reserve, no denominations are available to withdraw.`,
- {},
- );
- await incrementReserveRetry(ws, reserve.reservePub, opErr);
- throw new OperationFailedAndReportedError(opErr);
- }
- return;
- }
-
- logger.trace(
- `Selected coins total cost ${Amounts.stringify(
- denomsForWithdraw.totalWithdrawCost,
- )} for withdrawal of ${Amounts.stringify(withdrawAmount)}`,
- );
-
- logger.trace("selected denominations");
-
- const newWithdrawalGroup = await ws.db.runWithWriteTransaction(
- [
- Stores.withdrawalGroups,
- Stores.reserves,
- Stores.reserveHistory,
- Stores.planchets,
- ],
- async (tx) => {
- const newReserve = await tx.get(Stores.reserves, reservePub);
- if (!newReserve) {
- return false;
- }
- if (newReserve.reserveStatus !== ReserveRecordStatus.WITHDRAWING) {
- return false;
- }
- const newHist = await tx.get(Stores.reserveHistory, reservePub);
- if (!newHist) {
- throw Error("inconsistent database");
- }
- const newSummary = summarizeReserveHistory(
- newHist.reserveTransactions,
- newReserve.currency,
- );
- if (
- Amounts.cmp(
- newSummary.unclaimedReserveAmount,
- denomsForWithdraw.totalWithdrawCost,
- ) < 0
- ) {
- // Something must have happened concurrently!
- logger.error(
- "aborting withdrawal session, likely concurrent withdrawal happened",
- );
- logger.error(
- `unclaimed reserve amount is ${newSummary.unclaimedReserveAmount}`,
- );
- logger.error(
- `withdrawal cost is ${denomsForWithdraw.totalWithdrawCost}`,
- );
- return false;
- }
- for (let i = 0; i < denomsForWithdraw.selectedDenoms.length; i++) {
- const sd = denomsForWithdraw.selectedDenoms[i];
- for (let j = 0; j < sd.count; j++) {
- const amt = Amounts.add(sd.denom.value, sd.denom.feeWithdraw).amount;
- newHist.reserveTransactions.push({
- type: WalletReserveHistoryItemType.Withdraw,
- expectedAmount: amt,
- });
- }
- }
- newReserve.reserveStatus = ReserveRecordStatus.DORMANT;
- newReserve.retryInfo = initRetryInfo(false);
-
- let withdrawalGroupId: string;
-
- if (!newReserve.initialWithdrawalStarted) {
- withdrawalGroupId = newReserve.initialWithdrawalGroupId;
- newReserve.initialWithdrawalStarted = true;
- } else {
- withdrawalGroupId = encodeCrock(randomBytes(32));
- }
-
- const withdrawalRecord: WithdrawalGroupRecord = {
- withdrawalGroupId: withdrawalGroupId,
- exchangeBaseUrl: newReserve.exchangeBaseUrl,
- source: {
- type: WithdrawalSourceType.Reserve,
- reservePub: newReserve.reservePub,
- },
- rawWithdrawalAmount: withdrawAmount,
- timestampStart: getTimestampNow(),
- retryInfo: initRetryInfo(),
- lastErrorPerCoin: {},
- lastError: undefined,
- denomsSel: denomSelectionInfoToState(denomsForWithdraw),
- };
-
- await tx.put(Stores.reserves, newReserve);
- await tx.put(Stores.reserveHistory, newHist);
- await tx.put(Stores.withdrawalGroups, withdrawalRecord);
- return withdrawalRecord;
- },
- );
-
- if (newWithdrawalGroup) {
- logger.trace("processing new withdraw group");
- ws.notify({
- type: NotificationType.WithdrawGroupCreated,
- withdrawalGroupId: newWithdrawalGroup.withdrawalGroupId,
- });
- await processWithdrawGroup(ws, newWithdrawalGroup.withdrawalGroupId);
- } else {
- console.trace("withdraw session already existed");
- }
-}
-
-export async function createTalerWithdrawReserve(
- ws: InternalWalletState,
- talerWithdrawUri: string,
- selectedExchange: string,
-): Promise<AcceptWithdrawalResponse> {
- const withdrawInfo = await getBankWithdrawalInfo(ws, talerWithdrawUri);
- const exchangeWire = await getExchangePaytoUri(
- ws,
- selectedExchange,
- withdrawInfo.wireTypes,
- );
- const reserve = await createReserve(ws, {
- amount: withdrawInfo.amount,
- bankWithdrawStatusUrl: withdrawInfo.extractedStatusUrl,
- exchange: selectedExchange,
- senderWire: withdrawInfo.senderWire,
- exchangePaytoUri: exchangeWire,
- });
- // We do this here, as the reserve should be registered before we return,
- // so that we can redirect the user to the bank's status page.
- await processReserveBankStatus(ws, reserve.reservePub);
- return {
- reservePub: reserve.reservePub,
- confirmTransferUrl: withdrawInfo.confirmTransferUrl,
- };
-}
-
-/**
- * Get payto URIs needed to fund a reserve.
- */
-export async function getFundingPaytoUris(
- tx: TransactionHandle,
- reservePub: string,
-): Promise<string[]> {
- const r = await tx.get(Stores.reserves, reservePub);
- if (!r) {
- logger.error(`reserve ${reservePub} not found (DB corrupted?)`);
- return [];
- }
- const exchange = await tx.get(Stores.exchanges, r.exchangeBaseUrl);
- if (!exchange) {
- logger.error(`exchange ${r.exchangeBaseUrl} not found (DB corrupted?)`);
- return [];
- }
- const plainPaytoUris =
- exchange.wireInfo?.accounts.map((x) => x.payto_uri) ?? [];
- if (!plainPaytoUris) {
- logger.error(`exchange ${r.exchangeBaseUrl} has no wire info`);
- return [];
- }
- return plainPaytoUris.map((x) =>
- addPaytoQueryParams(x, {
- amount: Amounts.stringify(r.instructedAmount),
- message: `Taler Withdrawal ${r.reservePub}`,
- }),
- );
-}
diff --git a/src/operations/state.ts b/src/operations/state.ts
deleted file mode 100644
index cfec85d0f..000000000
--- a/src/operations/state.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- 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 { HttpRequestLibrary } from "../util/http";
-import { NextUrlResult, BalancesResponse } from "../types/walletTypes";
-import { CryptoApi, CryptoWorkerFactory } from "../crypto/workers/cryptoApi";
-import { AsyncOpMemoMap, AsyncOpMemoSingle } from "../util/asyncMemo";
-import { Logger } from "../util/logging";
-import { PendingOperationsResponse } from "../types/pending";
-import { WalletNotification } from "../types/notifications";
-import { Database } from "../util/query";
-
-type NotificationListener = (n: WalletNotification) => void;
-
-const logger = new Logger("state.ts");
-
-export class InternalWalletState {
- cachedNextUrl: { [fulfillmentUrl: string]: NextUrlResult } = {};
- memoProcessReserve: AsyncOpMemoMap<void> = new AsyncOpMemoMap();
- memoMakePlanchet: AsyncOpMemoMap<void> = new AsyncOpMemoMap();
- memoGetPending: AsyncOpMemoSingle<
- PendingOperationsResponse
- > = new AsyncOpMemoSingle();
- memoGetBalance: AsyncOpMemoSingle<BalancesResponse> = new AsyncOpMemoSingle();
- memoProcessRefresh: AsyncOpMemoMap<void> = new AsyncOpMemoMap();
- memoProcessRecoup: AsyncOpMemoMap<void> = new AsyncOpMemoMap();
- cryptoApi: CryptoApi;
-
- listeners: NotificationListener[] = [];
-
- constructor(
- public db: Database,
- public http: HttpRequestLibrary,
- cryptoWorkerFactory: CryptoWorkerFactory,
- ) {
- this.cryptoApi = new CryptoApi(cryptoWorkerFactory);
- }
-
- public notify(n: WalletNotification): void {
- logger.trace("Notification", n);
- for (const l of this.listeners) {
- const nc = JSON.parse(JSON.stringify(n));
- setTimeout(() => {
- l(nc);
- }, 0);
- }
- }
-
- addNotificationListener(f: (n: WalletNotification) => void): void {
- this.listeners.push(f);
- }
-}
diff --git a/src/operations/tip.ts b/src/operations/tip.ts
deleted file mode 100644
index 17f7ee90d..000000000
--- a/src/operations/tip.ts
+++ /dev/null
@@ -1,342 +0,0 @@
-/*
- 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;
-}
diff --git a/src/operations/transactions.ts b/src/operations/transactions.ts
deleted file mode 100644
index 647949d22..000000000
--- a/src/operations/transactions.ts
+++ /dev/null
@@ -1,292 +0,0 @@
-/*
- 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 { InternalWalletState } from "./state";
-import {
- Stores,
- WithdrawalSourceType,
-} from "../types/dbTypes";
-import { Amounts, AmountJson } from "../util/amounts";
-import { timestampCmp } from "../util/time";
-import {
- TransactionsRequest,
- TransactionsResponse,
- Transaction,
- TransactionType,
- PaymentStatus,
- WithdrawalType,
- WithdrawalDetails,
-} from "../types/transactions";
-import { getFundingPaytoUris } from "./reserves";
-
-/**
- * Create an event ID from the type and the primary key for the event.
- */
-function makeEventId(type: TransactionType, ...args: string[]): string {
- return type + ";" + args.map((x) => encodeURIComponent(x)).join(";");
-}
-
-function shouldSkipCurrency(
- transactionsRequest: TransactionsRequest | undefined,
- currency: string,
-): boolean {
- if (!transactionsRequest?.currency) {
- return false;
- }
- return transactionsRequest.currency.toLowerCase() !== currency.toLowerCase();
-}
-
-function shouldSkipSearch(
- transactionsRequest: TransactionsRequest | undefined,
- fields: string[],
-): boolean {
- if (!transactionsRequest?.search) {
- return false;
- }
- const needle = transactionsRequest.search.trim();
- for (const f of fields) {
- if (f.indexOf(needle) >= 0) {
- return false;
- }
- }
- return true;
-}
-
-/**
- * Retrive the full event history for this wallet.
- */
-export async function getTransactions(
- ws: InternalWalletState,
- transactionsRequest?: TransactionsRequest,
-): Promise<TransactionsResponse> {
- const transactions: Transaction[] = [];
-
- await ws.db.runWithReadTransaction(
- [
- Stores.currencies,
- Stores.coins,
- Stores.denominations,
- Stores.exchanges,
- Stores.proposals,
- Stores.purchases,
- Stores.refreshGroups,
- Stores.reserves,
- Stores.reserveHistory,
- Stores.tips,
- Stores.withdrawalGroups,
- Stores.payEvents,
- Stores.planchets,
- Stores.refundEvents,
- Stores.reserveUpdatedEvents,
- Stores.recoupGroups,
- ],
- // Report withdrawals that are currently in progress.
- async (tx) => {
- tx.iter(Stores.withdrawalGroups).forEachAsync(async (wsr) => {
- if (
- shouldSkipCurrency(
- transactionsRequest,
- wsr.rawWithdrawalAmount.currency,
- )
- ) {
- return;
- }
-
- if (shouldSkipSearch(transactionsRequest, [])) {
- return;
- }
-
- switch (wsr.source.type) {
- case WithdrawalSourceType.Reserve:
- {
- const r = await tx.get(Stores.reserves, wsr.source.reservePub);
- if (!r) {
- break;
- }
- let amountRaw: AmountJson | undefined = undefined;
- if (wsr.withdrawalGroupId === r.initialWithdrawalGroupId) {
- amountRaw = r.instructedAmount;
- } else {
- amountRaw = wsr.denomsSel.totalWithdrawCost;
- }
- let withdrawalDetails: WithdrawalDetails;
- if (r.bankInfo) {
- withdrawalDetails = {
- type: WithdrawalType.TalerBankIntegrationApi,
- confirmed: true,
- bankConfirmationUrl: r.bankInfo.confirmUrl,
- };
- } else {
- const exchange = await tx.get(
- Stores.exchanges,
- r.exchangeBaseUrl,
- );
- if (!exchange) {
- // FIXME: report somehow
- break;
- }
- withdrawalDetails = {
- type: WithdrawalType.ManualTransfer,
- exchangePaytoUris:
- exchange.wireInfo?.accounts.map((x) => x.payto_uri) ?? [],
- };
- }
- transactions.push({
- type: TransactionType.Withdrawal,
- amountEffective: Amounts.stringify(
- wsr.denomsSel.totalCoinValue,
- ),
- amountRaw: Amounts.stringify(amountRaw),
- withdrawalDetails,
- exchangeBaseUrl: wsr.exchangeBaseUrl,
- pending: !wsr.timestampFinish,
- timestamp: wsr.timestampStart,
- transactionId: makeEventId(
- TransactionType.Withdrawal,
- wsr.withdrawalGroupId,
- ),
- });
- }
- break;
- default:
- // Tips are reported via their own event
- break;
- }
- });
-
- // Report pending withdrawals based on reserves that
- // were created, but where the actual withdrawal group has
- // not started yet.
- tx.iter(Stores.reserves).forEachAsync(async (r) => {
- if (shouldSkipCurrency(transactionsRequest, r.currency)) {
- return;
- }
- if (shouldSkipSearch(transactionsRequest, [])) {
- return;
- }
- if (r.initialWithdrawalStarted) {
- return;
- }
- let withdrawalDetails: WithdrawalDetails;
- if (r.bankInfo) {
- withdrawalDetails = {
- type: WithdrawalType.TalerBankIntegrationApi,
- confirmed: false,
- bankConfirmationUrl: r.bankInfo.confirmUrl,
- };
- } else {
- withdrawalDetails = {
- type: WithdrawalType.ManualTransfer,
- exchangePaytoUris: await getFundingPaytoUris(tx, r.reservePub),
- };
- }
- transactions.push({
- type: TransactionType.Withdrawal,
- amountRaw: Amounts.stringify(r.instructedAmount),
- amountEffective: Amounts.stringify(r.initialDenomSel.totalCoinValue),
- exchangeBaseUrl: r.exchangeBaseUrl,
- pending: true,
- timestamp: r.timestampCreated,
- withdrawalDetails: withdrawalDetails,
- transactionId: makeEventId(
- TransactionType.Withdrawal,
- r.initialWithdrawalGroupId,
- ),
- });
- });
-
- tx.iter(Stores.purchases).forEachAsync(async (pr) => {
- if (
- shouldSkipCurrency(
- transactionsRequest,
- pr.contractData.amount.currency,
- )
- ) {
- return;
- }
- if (shouldSkipSearch(transactionsRequest, [pr.contractData.summary])) {
- return;
- }
- const proposal = await tx.get(Stores.proposals, pr.proposalId);
- if (!proposal) {
- return;
- }
- transactions.push({
- type: TransactionType.Payment,
- amountRaw: Amounts.stringify(pr.contractData.amount),
- amountEffective: Amounts.stringify(pr.payCostInfo.totalCost),
- status: pr.timestampFirstSuccessfulPay
- ? PaymentStatus.Paid
- : PaymentStatus.Accepted,
- pending: !pr.timestampFirstSuccessfulPay,
- timestamp: pr.timestampAccept,
- transactionId: makeEventId(TransactionType.Payment, pr.proposalId),
- info: {
- fulfillmentUrl: pr.contractData.fulfillmentUrl,
- merchant: pr.contractData.merchant,
- orderId: pr.contractData.orderId,
- products: pr.contractData.products,
- summary: pr.contractData.summary,
- summary_i18n: pr.contractData.summaryI18n,
- },
- });
-
- // for (const rg of pr.refundGroups) {
- // const pending = Object.keys(pr.refundsPending).length > 0;
- // const stats = getRefundStats(pr, rg.refundGroupId);
-
- // transactions.push({
- // type: TransactionType.Refund,
- // pending,
- // info: {
- // fulfillmentUrl: pr.contractData.fulfillmentUrl,
- // merchant: pr.contractData.merchant,
- // orderId: pr.contractData.orderId,
- // products: pr.contractData.products,
- // summary: pr.contractData.summary,
- // summary_i18n: pr.contractData.summaryI18n,
- // },
- // timestamp: rg.timestampQueried,
- // transactionId: makeEventId(
- // TransactionType.Refund,
- // pr.proposalId,
- // `${rg.timestampQueried.t_ms}`,
- // ),
- // refundedTransactionId: makeEventId(
- // TransactionType.Payment,
- // pr.proposalId,
- // ),
- // amountEffective: Amounts.stringify(stats.amountEffective),
- // amountInvalid: Amounts.stringify(stats.amountInvalid),
- // amountRaw: Amounts.stringify(stats.amountRaw),
- // });
- // }
-
- });
- },
- );
-
- const txPending = transactions.filter((x) => x.pending);
- const txNotPending = transactions.filter((x) => !x.pending);
-
- txPending.sort((h1, h2) => timestampCmp(h1.timestamp, h2.timestamp));
- txNotPending.sort((h1, h2) => timestampCmp(h1.timestamp, h2.timestamp));
-
- return { transactions: [...txPending, ...txNotPending] };
-}
diff --git a/src/operations/versions.ts b/src/operations/versions.ts
deleted file mode 100644
index 31c4921c6..000000000
--- a/src/operations/versions.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- 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/>
- */
-
-/**
- * Protocol version spoken with the exchange.
- *
- * Uses libtool's current:revision:age versioning.
- */
-export const WALLET_EXCHANGE_PROTOCOL_VERSION = "8:0:0";
-
-/**
- * Protocol version spoken with the merchant.
- *
- * Uses libtool's current:revision:age versioning.
- */
-export const WALLET_MERCHANT_PROTOCOL_VERSION = "1:0:0";
-
-/**
- * Cache breaker that is appended to queries such as /keys and /wire
- * to break through caching, if it has been accidentally/badly configured
- * by the exchange.
- *
- * This is only a temporary measure.
- */
-export const WALLET_CACHE_BREAKER_CLIENT_VERSION = "3";
diff --git a/src/operations/withdraw-test.ts b/src/operations/withdraw-test.ts
deleted file mode 100644
index 24cb6f4b1..000000000
--- a/src/operations/withdraw-test.ts
+++ /dev/null
@@ -1,332 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2020 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 test from "ava";
-import { getWithdrawDenomList } from "./withdraw";
-import { Amounts } from "../util/amounts";
-
-test("withdrawal selection bug repro", (t) => {
- const amount = {
- currency: "KUDOS",
- fraction: 43000000,
- value: 23,
- };
-
- const denoms = [
- {
- denomPub:
- "040000XT67C8KBD6B75TTQ3SK8FWXMNQW4372T3BDDGPAMB9RFCA03638W8T3F71WFEFK9NP32VKYVNFXPYRWQ1N1HDKV5J0DFEKHBPJCYSWCBJDRNWD7G8BN8PT97FA9AMV75MYEK4X54D1HGJ207JSVJBGFCATSPNTEYNHEQF1F220W00TBZR1HNPDQFD56FG0DJQ9KGHM8EC33H6AY9YN9CNX5R3Z4TZ4Q23W47SBHB13H6W74FQJG1F50X38VRSC4SR8RWBAFB7S4K8D2H4NMRFSQT892A3T0BTBW7HM5C0H2CK6FRKG31F7W9WP1S29013K5CXYE55CT8TH6N8J9B780R42Y5S3ZB6J6E9H76XBPSGH4TGYSR2VZRB98J417KCQMZKX1BB67E7W5KVE37TC9SJ904002",
- denomPubHash:
- "Q21FQSSG4FXNT96Z14CHXM8N1RZAG9GPHAV8PRWS0PZAAVWH7PBW6R97M2CH19KKP65NNSWXY7B6S53PT3CBM342E357ZXDDJ8RDVW8",
- exchangeBaseUrl: "https://exchange.demo.taler.net/",
- feeDeposit: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- feeRefresh: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- feeRefund: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- feeWithdraw: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- isOffered: true,
- isRevoked: false,
- masterSig:
- "4F0P456CNNTTWK8BFJHGM3JTD6FVVNZY8EP077GYAHDJ5Y81S5RQ3SMS925NXMDVG9A88JAAP0E2GDZBC21PP5NHFFVWHAW3AVT8J3R",
- stampExpireDeposit: {
- t_ms: 1742909388000,
- },
- stampExpireLegal: {
- t_ms: 1900589388000,
- },
- stampExpireWithdraw: {
- t_ms: 1679837388000,
- },
- stampStart: {
- t_ms: 1585229388000,
- },
- status: 0,
- value: {
- currency: "KUDOS",
- fraction: 0,
- value: 1000,
- },
- },
- {
- denomPub:
- "040000Y63CF78QFPKRY77BRK9P557Q1GQWX3NCZ3HSYSK0Z7TT0KGRA7N4SKBKEHSTVHX1Z9DNXMJR4EXSY1TXCKV0GJ3T3YYC6Z0JNMJFVYQAV4FX5J90NZH1N33MZTV8HS9SMNAA9S6K73G4P99GYBB01B0P6M1KXZ5JRDR7VWBR3MEJHHGJ6QBMCJR3NWJRE3WJW9PRY8QPQ2S7KFWTWRESH2DBXCXWBD2SRN6P9YX8GRAEMFEGXC9V5GVJTEMH6ZDGNXFPWZE3JVJ2Q4N9GDYKBCHZCJ7M7M2RJ9ZV4Y64NAN9BT6XDC68215GKKRHTW1BBF1MYY6AR3JCTT9HYAM923RMVQR3TAEB7SDX8J76XRZWYH3AGJCZAQGMN5C8SSH9AHQ9RNQJQ15CN45R37X4YNFJV904002",
- denomPubHash:
- "447WA23SCBATMABHA0793F92MYTBYVPYMMQHCPKMKVY5P7RZRFMQ6VRW0Y8HRA7177GTBT0TBT08R21DZD129AJ995H9G09XBFE55G8",
- exchangeBaseUrl: "https://exchange.demo.taler.net/",
- feeDeposit: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- feeRefresh: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- feeRefund: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- feeWithdraw: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- isOffered: true,
- isRevoked: false,
- masterSig:
- "P99AW82W46MZ0AKW7Z58VQPXFNTJQM9DVTYPBDF6KVYF38PPVDAZTV7JQ8TY7HGEC7JJJAY4E7AY7J3W1WV10DAZZQHHKTAVTSRAC20",
- stampExpireDeposit: {
- t_ms: 1742909388000,
- },
- stampExpireLegal: {
- t_ms: 1900589388000,
- },
- stampExpireWithdraw: {
- t_ms: 1679837388000,
- },
- stampStart: {
- t_ms: 1585229388000,
- },
- status: 0,
- value: {
- currency: "KUDOS",
- fraction: 0,
- value: 10,
- },
- },
- {
- denomPub:
- "040000YDESWC2B962DA4WK356SC50MA3N9KV0ZSGY3RC48JCTY258W909C7EEMT5BTC5KZ5T4CERCZ141P9QF87EK2BD1XEEM5GB07MB3H19WE4CQGAS8X84JBWN83PQGQXVMWE5HFA992KMGHC566GT9ZS2QPHZB6X89C4A80Z663PYAAPXP728VHAKATGNNBQ01ZZ2XD1CH9Y38YZBSPJ4K7GB2J76GBCYAVD9ENHDVWXJAXYRPBX4KSS5TXRR3K5NEN9ZV3AJD2V65K7ABRZDF5D5V1FJZZMNJ5XZ4FEREEKEBV9TDFPGJTKDEHEC60K3DN24DAATRESDJ1ZYYSYSRCAT4BT2B62ARGVMJTT5N2R126DRW9TGRWCW0ZAF2N2WET1H4NJEW77X0QT46Z5R3MZ0XPHD04002",
- denomPubHash:
- "JS61DTKAFM0BX8Q4XV3ZSKB921SM8QK745Z2AFXTKFMBHHFNBD8TQ5ETJHFNDGBGX22FFN2A2ERNYG1SGSDQWNQHQQ2B14DBVJYJG8R",
- exchangeBaseUrl: "https://exchange.demo.taler.net/",
- feeDeposit: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- feeRefresh: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- feeRefund: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- feeWithdraw: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- isOffered: true,
- isRevoked: false,
- masterSig:
- "8S4VZGHE5WE0N5ZVCHYW9KZZR4YAKK15S46MV1HR1QB9AAMH3NWPW4DCR4NYGJK33Q8YNFY80SWNS6XKAP5DEVK933TM894FJ2VGE3G",
- stampExpireDeposit: {
- t_ms: 1742909388000,
- },
- stampExpireLegal: {
- t_ms: 1900589388000,
- },
- stampExpireWithdraw: {
- t_ms: 1679837388000,
- },
- stampStart: {
- t_ms: 1585229388000,
- },
- status: 0,
- value: {
- currency: "KUDOS",
- fraction: 0,
- value: 5,
- },
- },
- {
- denomPub:
- "040000YG3T1ADB8DVA6BD3EPV6ZHSHTDW35DEN4VH1AE6CSB7P1PSDTNTJG866PHF6QB1CCWYCVRGA0FVBJ9Q0G7KV7AD9010GDYBQH0NNPHW744MTNXVXWBGGGRGQGYK4DTYN1DSWQ1FZNDSZZPB5BEKG2PDJ93NX2JTN06Y8QMS2G734Z9XHC10EENBG2KVB7EJ3CM8PV1T32RC7AY62F3496E8D8KRHJQQTT67DSGMNKK86QXVDTYW677FG27DP20E8XY3M6FQD53NDJ1WWES91401MV1A3VXVPGC76GZVDD62W3WTJ1YMKHTTA3MRXX3VEAAH3XTKDN1ER7X6CZPMYTF8VK735VP2B2TZGTF28TTW4FZS32SBS64APCDF6SZQ427N5538TJC7SRE71YSP5ET8GS904002",
- denomPubHash:
- "8T51NEY81VMPQ180EQ5WR0YH7GMNNT90W55Q0514KZM18AZT71FHJGJHQXGK0WTA7ACN1X2SD0S53XPBQ1A9KH960R48VCVVM6E3TH8",
- exchangeBaseUrl: "https://exchange.demo.taler.net/",
- feeDeposit: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- feeRefresh: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- feeRefund: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- feeWithdraw: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- isOffered: true,
- isRevoked: false,
- masterSig:
- "E3AWGAG8VB42P3KXM8B04Z6M483SX59R3Y4T53C3NXCA2NPB6C7HVCMVX05DC6S58E9X40NGEBQNYXKYMYCF3ASY2C4WP1WCZ4ME610",
- stampExpireDeposit: {
- t_ms: 1742909388000,
- },
- stampExpireLegal: {
- t_ms: 1900589388000,
- },
- stampExpireWithdraw: {
- t_ms: 1679837388000,
- },
- stampStart: {
- t_ms: 1585229388000,
- },
- status: 0,
- value: {
- currency: "KUDOS",
- fraction: 0,
- value: 1,
- },
- },
- {
- denomPub:
- "040000ZC0G60E9QQ5PD81TSDWD9GV5Y6P8Z05NSPA696DP07NGQQVSRQXBA76Q6PRB0YFX295RG4MTQJXAZZ860ET307HSC2X37XAVGQXRVB8Q4F1V7NP5ZEVKTX75DZK1QRAVHEZGQYKSSH6DBCJNQF6V9WNQF3GEYVA4KCBHA7JF772KHXM9642C28Z0AS4XXXV2PABAN5C8CHYD5H7JDFNK3920W5Q69X0BS84XZ4RE2PW6HM1WZ6KGZ3MKWWWCPKQ1FSFABRBWKAB09PF563BEBXKY6M38QETPH5EDWGANHD0SC3QV0WXYVB7BNHNNQ0J5BNV56K563SYHM4E5ND260YRJSYA1GN5YSW2B1J5T1A1EBNYF2DN6JNJKWXWEQ42G5YS17ZSZ5EWDRA9QKV8EGTCNAD04002",
- denomPubHash:
- "A41HW0Q2H9PCNMEWW0C0N45QAYVXZ8SBVRRAHE4W6X24SV1TH38ANTWDT80JXEBW9Z8PVPGT9GFV2EYZWJ5JW5W1N34NFNKHQSZ1PFR",
- exchangeBaseUrl: "https://exchange.demo.taler.net/",
- feeDeposit: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- feeRefresh: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- feeRefund: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- feeWithdraw: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- isOffered: true,
- isRevoked: false,
- masterSig:
- "0ES1RKV002XB4YP21SN0QB7RSDHGYT0XAE65JYN8AVJAA6H7JZFN7JADXT521DJS89XMGPZGR8GCXF1516Y0Q9QDV00E6NMFA6CF838",
- stampExpireDeposit: {
- t_ms: 1742909388000,
- },
- stampExpireLegal: {
- t_ms: 1900589388000,
- },
- stampExpireWithdraw: {
- t_ms: 1679837388000,
- },
- stampStart: {
- t_ms: 1585229388000,
- },
- status: 0,
- value: {
- currency: "KUDOS",
- fraction: 10000000,
- value: 0,
- },
- },
- {
- denomPub:
- "040000ZSK2PMVY6E3NBQ52KXMW029M60F4BWYTDS0FZSD0PE53CNZ9H6TM3GQK1WRTEKQ5GRWJ1J9DY6Y42SP47QVT1XD1G0W05SQ5F3F7P5KSWR0FJBJ9NZBXQEVN8Q4JRC94X3JJ3XV3KBYTZ2HTDFV28C3H2SRR0XGNZB4FY85NDZF1G4AEYJJ9QB3C0V8H70YB8RV3FKTNH7XS4K4HFNZHJ5H9VMX5SM9Z2DX37HA5WFH0E2MJBVVF2BWWA5M0HPPSB365RAE2AMD42Q65A96WD80X27SB2ZNQZ8WX0K13FWF85GZ6YNYAJGE1KGN06JDEKE9QD68Z651D7XE8V6664TVVC8M68S7WD0DSXMJQKQ0BNJXNDE29Q7MRX6DA3RW0PZ44B3TKRK0294FPVZTNSTA6XF04002",
- denomPubHash:
- "F5NGBX33DTV4595XZZVK0S2MA1VMXFEJQERE5EBP5DS4QQ9EFRANN7YHWC1TKSHT2K6CQWDBRES8D3DWR0KZF5RET40B4AZXZ0RW1ZG",
- exchangeBaseUrl: "https://exchange.demo.taler.net/",
- feeDeposit: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- feeRefresh: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- feeRefund: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- feeWithdraw: {
- currency: "KUDOS",
- fraction: 1000000,
- value: 0,
- },
- isOffered: true,
- isRevoked: false,
- masterSig:
- "58QEB6C6N7602E572E3JYANVVJ9BRW0V9E2ZFDW940N47YVQDK9SAFPWBN5YGT3G1742AFKQ0CYR4DM2VWV0Z0T1XMEKWN6X2EZ9M0R",
- stampExpireDeposit: {
- t_ms: 1742909388000,
- },
- stampExpireLegal: {
- t_ms: 1900589388000,
- },
- stampExpireWithdraw: {
- t_ms: 1679837388000,
- },
- stampStart: {
- t_ms: 1585229388000,
- },
- status: 0,
- value: {
- currency: "KUDOS",
- fraction: 0,
- value: 2,
- },
- },
- ];
-
- const res = getWithdrawDenomList(amount, denoms);
-
- console.error("cost", Amounts.stringify(res.totalWithdrawCost));
- console.error("withdraw amount", Amounts.stringify(amount));
-
- t.assert(Amounts.cmp(res.totalWithdrawCost, amount) <= 0);
- t.pass();
-});
diff --git a/src/operations/withdraw.ts b/src/operations/withdraw.ts
deleted file mode 100644
index 486375300..000000000
--- a/src/operations/withdraw.ts
+++ /dev/null
@@ -1,756 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2019-2020 Taler Systems SA
-
- 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, Amounts } from "../util/amounts";
-import {
- DenominationRecord,
- Stores,
- DenominationStatus,
- CoinStatus,
- CoinRecord,
- initRetryInfo,
- updateRetryInfoTimeout,
- CoinSourceType,
- DenominationSelectionInfo,
- PlanchetRecord,
- WithdrawalSourceType,
- DenomSelectionState,
-} from "../types/dbTypes";
-import {
- BankWithdrawDetails,
- ExchangeWithdrawDetails,
- OperationErrorDetails,
- ExchangeListItem,
-} from "../types/walletTypes";
-import {
- codecForWithdrawOperationStatusResponse,
- codecForWithdrawResponse,
- WithdrawUriInfoResponse,
-} from "../types/talerTypes";
-import { InternalWalletState } from "./state";
-import { parseWithdrawUri } from "../util/taleruri";
-import { Logger } from "../util/logging";
-import { updateExchangeFromUrl, getExchangeTrust } from "./exchanges";
-import { WALLET_EXCHANGE_PROTOCOL_VERSION } from "./versions";
-
-import * as LibtoolVersion from "../util/libtoolVersion";
-import { guardOperationException } from "./errors";
-import { NotificationType } from "../types/notifications";
-import {
- getTimestampNow,
- getDurationRemaining,
- timestampCmp,
- timestampSubtractDuraction,
-} from "../util/time";
-import { readSuccessResponseJsonOrThrow } from "../util/http";
-
-const logger = new Logger("withdraw.ts");
-
-function isWithdrawableDenom(d: DenominationRecord): boolean {
- const now = getTimestampNow();
- const started = timestampCmp(now, d.stampStart) >= 0;
- const lastPossibleWithdraw = timestampSubtractDuraction(
- d.stampExpireWithdraw,
- { d_ms: 50 * 1000 },
- );
- const remaining = getDurationRemaining(lastPossibleWithdraw, now);
- const stillOkay = remaining.d_ms !== 0;
- return started && stillOkay && !d.isRevoked;
-}
-
-/**
- * Get a list of denominations (with repetitions possible)
- * whose total value is as close as possible to the available
- * amount, but never larger.
- */
-export function getWithdrawDenomList(
- amountAvailable: AmountJson,
- denoms: DenominationRecord[],
-): DenominationSelectionInfo {
- let remaining = Amounts.copy(amountAvailable);
-
- const selectedDenoms: {
- count: number;
- denom: DenominationRecord;
- }[] = [];
-
- let totalCoinValue = Amounts.getZero(amountAvailable.currency);
- let totalWithdrawCost = Amounts.getZero(amountAvailable.currency);
-
- denoms = denoms.filter(isWithdrawableDenom);
- denoms.sort((d1, d2) => Amounts.cmp(d2.value, d1.value));
-
- for (const d of denoms) {
- let count = 0;
- const cost = Amounts.add(d.value, d.feeWithdraw).amount;
- for (;;) {
- if (Amounts.cmp(remaining, cost) < 0) {
- break;
- }
- remaining = Amounts.sub(remaining, cost).amount;
- count++;
- }
- if (count > 0) {
- totalCoinValue = Amounts.add(
- totalCoinValue,
- Amounts.mult(d.value, count).amount,
- ).amount;
- totalWithdrawCost = Amounts.add(
- totalWithdrawCost,
- Amounts.mult(cost, count).amount,
- ).amount;
- selectedDenoms.push({
- count,
- denom: d,
- });
- }
-
- if (Amounts.isZero(remaining)) {
- break;
- }
- }
-
- return {
- selectedDenoms,
- totalCoinValue,
- totalWithdrawCost,
- };
-}
-
-/**
- * Get information about a withdrawal from
- * a taler://withdraw URI by asking the bank.
- */
-export async function getBankWithdrawalInfo(
- ws: InternalWalletState,
- talerWithdrawUri: string,
-): Promise<BankWithdrawDetails> {
- const uriResult = parseWithdrawUri(talerWithdrawUri);
- if (!uriResult) {
- throw Error(`can't parse URL ${talerWithdrawUri}`);
- }
- const reqUrl = new URL(
- `api/withdraw-operation/${uriResult.withdrawalOperationId}`,
- uriResult.bankIntegrationApiBaseUrl,
- );
- const resp = await ws.http.get(reqUrl.href);
- const status = await readSuccessResponseJsonOrThrow(
- resp,
- codecForWithdrawOperationStatusResponse(),
- );
-
- return {
- amount: Amounts.parseOrThrow(status.amount),
- confirmTransferUrl: status.confirm_transfer_url,
- extractedStatusUrl: reqUrl.href,
- selectionDone: status.selection_done,
- senderWire: status.sender_wire,
- suggestedExchange: status.suggested_exchange,
- transferDone: status.transfer_done,
- wireTypes: status.wire_types,
- };
-}
-
-/**
- * Return denominations that can potentially used for a withdrawal.
- */
-async function getPossibleDenoms(
- ws: InternalWalletState,
- exchangeBaseUrl: string,
-): Promise<DenominationRecord[]> {
- return await ws.db
- .iterIndex(Stores.denominations.exchangeBaseUrlIndex, exchangeBaseUrl)
- .filter((d) => {
- return (
- (d.status === DenominationStatus.Unverified ||
- d.status === DenominationStatus.VerifiedGood) &&
- !d.isRevoked
- );
- });
-}
-
-/**
- * Given a planchet, withdraw a coin from the exchange.
- */
-async function processPlanchet(
- ws: InternalWalletState,
- withdrawalGroupId: string,
- coinIdx: number,
-): Promise<void> {
- const withdrawalGroup = await ws.db.get(
- Stores.withdrawalGroups,
- withdrawalGroupId,
- );
- if (!withdrawalGroup) {
- return;
- }
- let planchet = await ws.db.getIndexed(Stores.planchets.byGroupAndIndex, [
- withdrawalGroupId,
- coinIdx,
- ]);
- if (!planchet) {
- let ci = 0;
- let denomPubHash: string | undefined;
- for (
- let di = 0;
- di < withdrawalGroup.denomsSel.selectedDenoms.length;
- di++
- ) {
- const d = withdrawalGroup.denomsSel.selectedDenoms[di];
- if (coinIdx >= ci && coinIdx < ci + d.count) {
- denomPubHash = d.denomPubHash;
- break;
- }
- ci += d.count;
- }
- if (!denomPubHash) {
- throw Error("invariant violated");
- }
- const denom = await ws.db.getIndexed(
- Stores.denominations.denomPubHashIndex,
- denomPubHash,
- );
- if (!denom) {
- throw Error("invariant violated");
- }
- if (withdrawalGroup.source.type != WithdrawalSourceType.Reserve) {
- throw Error("invariant violated");
- }
- const reserve = await ws.db.get(
- Stores.reserves,
- withdrawalGroup.source.reservePub,
- );
- if (!reserve) {
- throw Error("invariant violated");
- }
- const r = await ws.cryptoApi.createPlanchet({
- denomPub: denom.denomPub,
- feeWithdraw: denom.feeWithdraw,
- reservePriv: reserve.reservePriv,
- reservePub: reserve.reservePub,
- value: denom.value,
- });
- const newPlanchet: PlanchetRecord = {
- blindingKey: r.blindingKey,
- coinEv: r.coinEv,
- coinEvHash: r.coinEvHash,
- coinIdx,
- coinPriv: r.coinPriv,
- coinPub: r.coinPub,
- coinValue: r.coinValue,
- denomPub: r.denomPub,
- denomPubHash: r.denomPubHash,
- isFromTip: false,
- reservePub: r.reservePub,
- withdrawalDone: false,
- withdrawSig: r.withdrawSig,
- withdrawalGroupId: withdrawalGroupId,
- };
- await ws.db.runWithWriteTransaction([Stores.planchets], async (tx) => {
- const p = await tx.getIndexed(Stores.planchets.byGroupAndIndex, [
- withdrawalGroupId,
- coinIdx,
- ]);
- if (p) {
- planchet = p;
- return;
- }
- await tx.put(Stores.planchets, newPlanchet);
- planchet = newPlanchet;
- });
- }
- if (!planchet) {
- throw Error("invariant violated");
- }
- if (planchet.withdrawalDone) {
- logger.warn("processPlanchet: planchet already withdrawn");
- return;
- }
- const exchange = await ws.db.get(
- Stores.exchanges,
- withdrawalGroup.exchangeBaseUrl,
- );
- if (!exchange) {
- logger.error("db inconsistent: exchange for planchet not found");
- return;
- }
-
- const denom = await ws.db.get(Stores.denominations, [
- withdrawalGroup.exchangeBaseUrl,
- planchet.denomPub,
- ]);
-
- if (!denom) {
- console.error("db inconsistent: denom for planchet not found");
- return;
- }
-
- logger.trace(
- `processing planchet #${coinIdx} in withdrawal ${withdrawalGroupId}`,
- );
-
- const wd: any = {};
- wd.denom_pub_hash = planchet.denomPubHash;
- wd.reserve_pub = planchet.reservePub;
- wd.reserve_sig = planchet.withdrawSig;
- wd.coin_ev = planchet.coinEv;
- const reqUrl = new URL(
- `reserves/${planchet.reservePub}/withdraw`,
- exchange.baseUrl,
- ).href;
-
- const resp = await ws.http.postJson(reqUrl, wd);
- const r = await readSuccessResponseJsonOrThrow(
- resp,
- codecForWithdrawResponse(),
- );
-
- logger.trace(`got response for /withdraw`);
-
- const denomSig = await ws.cryptoApi.rsaUnblind(
- r.ev_sig,
- planchet.blindingKey,
- planchet.denomPub,
- );
-
- const isValid = await ws.cryptoApi.rsaVerify(
- planchet.coinPub,
- denomSig,
- planchet.denomPub,
- );
-
- if (!isValid) {
- throw Error("invalid RSA signature by the exchange");
- }
-
- logger.trace(`unblinded and verified`);
-
- const coin: CoinRecord = {
- blindingKey: planchet.blindingKey,
- coinPriv: planchet.coinPriv,
- coinPub: planchet.coinPub,
- currentAmount: planchet.coinValue,
- denomPub: planchet.denomPub,
- denomPubHash: planchet.denomPubHash,
- denomSig,
- exchangeBaseUrl: withdrawalGroup.exchangeBaseUrl,
- status: CoinStatus.Fresh,
- coinSource: {
- type: CoinSourceType.Withdraw,
- coinIndex: coinIdx,
- reservePub: planchet.reservePub,
- withdrawalGroupId: withdrawalGroupId,
- },
- suspended: false,
- };
-
- let withdrawalGroupFinished = false;
-
- const planchetCoinPub = planchet.coinPub;
-
- const success = await ws.db.runWithWriteTransaction(
- [Stores.coins, Stores.withdrawalGroups, Stores.reserves, Stores.planchets],
- async (tx) => {
- const ws = await tx.get(Stores.withdrawalGroups, withdrawalGroupId);
- if (!ws) {
- return false;
- }
- const p = await tx.get(Stores.planchets, planchetCoinPub);
- if (!p) {
- return false;
- }
- if (p.withdrawalDone) {
- // Already withdrawn
- return false;
- }
- p.withdrawalDone = true;
- await tx.put(Stores.planchets, p);
-
- let numTotal = 0;
-
- for (const ds of ws.denomsSel.selectedDenoms) {
- numTotal += ds.count;
- }
-
- let numDone = 0;
-
- await tx
- .iterIndexed(Stores.planchets.byGroup, withdrawalGroupId)
- .forEach((x) => {
- if (x.withdrawalDone) {
- numDone++;
- }
- });
-
- if (numDone > numTotal) {
- throw Error(
- "invariant violated (created more planchets than expected)",
- );
- }
-
- if (numDone == numTotal) {
- ws.timestampFinish = getTimestampNow();
- ws.lastError = undefined;
- ws.retryInfo = initRetryInfo(false);
- withdrawalGroupFinished = true;
- }
- await tx.put(Stores.withdrawalGroups, ws);
- await tx.add(Stores.coins, coin);
- return true;
- },
- );
-
- logger.trace(`withdrawal result stored in DB`);
-
- if (success) {
- ws.notify({
- type: NotificationType.CoinWithdrawn,
- });
- }
-
- if (withdrawalGroupFinished) {
- ws.notify({
- type: NotificationType.WithdrawGroupFinished,
- withdrawalSource: withdrawalGroup.source,
- });
- }
-}
-
-export function denomSelectionInfoToState(
- dsi: DenominationSelectionInfo,
-): DenomSelectionState {
- return {
- selectedDenoms: dsi.selectedDenoms.map((x) => {
- return {
- count: x.count,
- denomPubHash: x.denom.denomPubHash,
- };
- }),
- totalCoinValue: dsi.totalCoinValue,
- totalWithdrawCost: dsi.totalWithdrawCost,
- };
-}
-
-/**
- * Get a list of denominations to withdraw from the given exchange for the
- * given amount, making sure that all denominations' signatures are verified.
- *
- * Writes to the DB in order to record the result from verifying
- * denominations.
- */
-export async function selectWithdrawalDenoms(
- ws: InternalWalletState,
- exchangeBaseUrl: string,
- amount: AmountJson,
-): Promise<DenominationSelectionInfo> {
- const exchange = await ws.db.get(Stores.exchanges, exchangeBaseUrl);
- if (!exchange) {
- logger.error("exchange not found");
- throw Error(`exchange ${exchangeBaseUrl} not found`);
- }
- const exchangeDetails = exchange.details;
- if (!exchangeDetails) {
- logger.error("exchange details not available");
- throw Error(`exchange ${exchangeBaseUrl} details not available`);
- }
-
- let allValid = false;
- let selectedDenoms: DenominationSelectionInfo;
-
- // Find a denomination selection for the requested amount.
- // If a selected denomination has not been validated yet
- // and turns our to be invalid, we try again with the
- // reduced set of denominations.
- do {
- allValid = true;
- const nextPossibleDenoms = await getPossibleDenoms(ws, exchange.baseUrl);
- selectedDenoms = getWithdrawDenomList(amount, nextPossibleDenoms);
- for (const denomSel of selectedDenoms.selectedDenoms) {
- const denom = denomSel.denom;
- if (denom.status === DenominationStatus.Unverified) {
- const valid = await ws.cryptoApi.isValidDenom(
- denom,
- exchangeDetails.masterPublicKey,
- );
- if (!valid) {
- denom.status = DenominationStatus.VerifiedBad;
- allValid = false;
- } else {
- denom.status = DenominationStatus.VerifiedGood;
- }
- await ws.db.put(Stores.denominations, denom);
- }
- }
- } while (selectedDenoms.selectedDenoms.length > 0 && !allValid);
-
- if (Amounts.cmp(selectedDenoms.totalWithdrawCost, amount) > 0) {
- throw Error("Bug: withdrawal coin selection is wrong");
- }
-
- return selectedDenoms;
-}
-
-async function incrementWithdrawalRetry(
- ws: InternalWalletState,
- withdrawalGroupId: string,
- err: OperationErrorDetails | undefined,
-): Promise<void> {
- await ws.db.runWithWriteTransaction([Stores.withdrawalGroups], async (tx) => {
- const wsr = await tx.get(Stores.withdrawalGroups, withdrawalGroupId);
- if (!wsr) {
- return;
- }
- if (!wsr.retryInfo) {
- return;
- }
- wsr.retryInfo.retryCounter++;
- updateRetryInfoTimeout(wsr.retryInfo);
- wsr.lastError = err;
- await tx.put(Stores.withdrawalGroups, wsr);
- });
- if (err) {
- ws.notify({ type: NotificationType.WithdrawOperationError, error: err });
- }
-}
-
-export async function processWithdrawGroup(
- ws: InternalWalletState,
- withdrawalGroupId: string,
- forceNow = false,
-): Promise<void> {
- const onOpErr = (e: OperationErrorDetails): Promise<void> =>
- incrementWithdrawalRetry(ws, withdrawalGroupId, e);
- await guardOperationException(
- () => processWithdrawGroupImpl(ws, withdrawalGroupId, forceNow),
- onOpErr,
- );
-}
-
-async function resetWithdrawalGroupRetry(
- ws: InternalWalletState,
- withdrawalGroupId: string,
-): Promise<void> {
- await ws.db.mutate(Stores.withdrawalGroups, withdrawalGroupId, (x) => {
- if (x.retryInfo.active) {
- x.retryInfo = initRetryInfo();
- }
- return x;
- });
-}
-
-async function processInBatches(
- workGen: Iterator<Promise<void>>,
- batchSize: number,
-): Promise<void> {
- for (;;) {
- const batch: Promise<void>[] = [];
- for (let i = 0; i < batchSize; i++) {
- const wn = workGen.next();
- if (wn.done) {
- break;
- }
- batch.push(wn.value);
- }
- if (batch.length == 0) {
- break;
- }
- logger.trace(`processing withdrawal batch of ${batch.length} elements`);
- await Promise.all(batch);
- }
-}
-
-async function processWithdrawGroupImpl(
- ws: InternalWalletState,
- withdrawalGroupId: string,
- forceNow: boolean,
-): Promise<void> {
- logger.trace("processing withdraw group", withdrawalGroupId);
- if (forceNow) {
- await resetWithdrawalGroupRetry(ws, withdrawalGroupId);
- }
- const withdrawalGroup = await ws.db.get(
- Stores.withdrawalGroups,
- withdrawalGroupId,
- );
- if (!withdrawalGroup) {
- logger.trace("withdraw session doesn't exist");
- return;
- }
-
- const numDenoms = withdrawalGroup.denomsSel.selectedDenoms.length;
- const genWork = function* (): Iterator<Promise<void>> {
- let coinIdx = 0;
- for (let i = 0; i < numDenoms; i++) {
- const count = withdrawalGroup.denomsSel.selectedDenoms[i].count;
- for (let j = 0; j < count; j++) {
- yield processPlanchet(ws, withdrawalGroupId, coinIdx);
- coinIdx++;
- }
- }
- };
-
- // Withdraw coins in batches.
- // The batch size is relatively large
- await processInBatches(genWork(), 10);
-}
-
-export async function getExchangeWithdrawalInfo(
- ws: InternalWalletState,
- baseUrl: string,
- amount: AmountJson,
-): Promise<ExchangeWithdrawDetails> {
- const exchangeInfo = await updateExchangeFromUrl(ws, baseUrl);
- const exchangeDetails = exchangeInfo.details;
- if (!exchangeDetails) {
- throw Error(`exchange ${exchangeInfo.baseUrl} details not available`);
- }
- const exchangeWireInfo = exchangeInfo.wireInfo;
- if (!exchangeWireInfo) {
- throw Error(`exchange ${exchangeInfo.baseUrl} wire details not available`);
- }
-
- const selectedDenoms = await selectWithdrawalDenoms(ws, baseUrl, amount);
- const exchangeWireAccounts: string[] = [];
- for (const account of exchangeWireInfo.accounts) {
- exchangeWireAccounts.push(account.payto_uri);
- }
-
- const { isTrusted, isAudited } = await getExchangeTrust(ws, exchangeInfo);
-
- let earliestDepositExpiration =
- selectedDenoms.selectedDenoms[0].denom.stampExpireDeposit;
- for (let i = 1; i < selectedDenoms.selectedDenoms.length; i++) {
- const expireDeposit =
- selectedDenoms.selectedDenoms[i].denom.stampExpireDeposit;
- if (expireDeposit.t_ms < earliestDepositExpiration.t_ms) {
- earliestDepositExpiration = expireDeposit;
- }
- }
-
- const possibleDenoms = await ws.db
- .iterIndex(Stores.denominations.exchangeBaseUrlIndex, baseUrl)
- .filter((d) => d.isOffered);
-
- const trustedAuditorPubs = [];
- const currencyRecord = await ws.db.get(Stores.currencies, amount.currency);
- if (currencyRecord) {
- trustedAuditorPubs.push(
- ...currencyRecord.auditors.map((a) => a.auditorPub),
- );
- }
-
- let versionMatch;
- if (exchangeDetails.protocolVersion) {
- versionMatch = LibtoolVersion.compare(
- WALLET_EXCHANGE_PROTOCOL_VERSION,
- exchangeDetails.protocolVersion,
- );
-
- if (
- versionMatch &&
- !versionMatch.compatible &&
- versionMatch.currentCmp === -1
- ) {
- console.warn(
- `wallet's support for exchange protocol version ${WALLET_EXCHANGE_PROTOCOL_VERSION} might be outdated ` +
- `(exchange has ${exchangeDetails.protocolVersion}), checking for updates`,
- );
- }
- }
-
- let tosAccepted = false;
-
- if (exchangeInfo.termsOfServiceAcceptedTimestamp) {
- if (
- exchangeInfo.termsOfServiceAcceptedEtag ==
- exchangeInfo.termsOfServiceLastEtag
- ) {
- tosAccepted = true;
- }
- }
-
- const withdrawFee = Amounts.sub(
- selectedDenoms.totalWithdrawCost,
- selectedDenoms.totalCoinValue,
- ).amount;
-
- const ret: ExchangeWithdrawDetails = {
- earliestDepositExpiration,
- exchangeInfo,
- exchangeWireAccounts,
- exchangeVersion: exchangeDetails.protocolVersion || "unknown",
- isAudited,
- isTrusted,
- numOfferedDenoms: possibleDenoms.length,
- overhead: Amounts.sub(amount, selectedDenoms.totalWithdrawCost).amount,
- selectedDenoms,
- trustedAuditorPubs,
- versionMatch,
- walletVersion: WALLET_EXCHANGE_PROTOCOL_VERSION,
- wireFees: exchangeWireInfo,
- withdrawFee,
- termsOfServiceAccepted: tosAccepted,
- };
- return ret;
-}
-
-export async function getWithdrawalDetailsForUri(
- ws: InternalWalletState,
- talerWithdrawUri: string,
-): Promise<WithdrawUriInfoResponse> {
- const info = await getBankWithdrawalInfo(ws, talerWithdrawUri);
- if (info.suggestedExchange) {
- // FIXME: right now the exchange gets permanently added,
- // we might want to only temporarily add it.
- try {
- await updateExchangeFromUrl(ws, info.suggestedExchange);
- } catch (e) {
- // We still continued if it failed, as other exchanges might be available.
- // We don't want to fail if the bank-suggested exchange is broken/offline.
- logger.trace(`querying bank-suggested exchange (${info.suggestedExchange}) failed`)
- }
- }
-
- const exchangesRes: (ExchangeListItem | undefined)[] = await ws.db
- .iter(Stores.exchanges)
- .map((x) => {
- const details = x.details;
- if (!details) {
- return undefined;
- }
- if (!x.addComplete) {
- return undefined;
- }
- if (!x.wireInfo) {
- return undefined;
- }
- if (details.currency !== info.amount.currency) {
- return undefined;
- }
- return {
- exchangeBaseUrl: x.baseUrl,
- currency: details.currency,
- paytoUris: x.wireInfo.accounts.map((x) => x.payto_uri),
- };
- });
- const exchanges = exchangesRes.filter((x) => !!x) as ExchangeListItem[];
-
- return {
- amount: Amounts.stringify(info.amount),
- defaultExchangeBaseUrl: info.suggestedExchange,
- possibleExchanges: exchanges,
- }
-}
diff --git a/src/types/ReserveStatus.ts b/src/types/ReserveStatus.ts
deleted file mode 100644
index 18601b9a7..000000000
--- a/src/types/ReserveStatus.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- 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/>
- */
-
-/**
- * @author Florian Dold <dold@taler.net>
- */
-
-/**
- * Imports.
- */
-import {
- codecForString,
- makeCodecForObject,
- makeCodecForList,
- Codec,
-} from "../util/codec";
-import { AmountString } from "./talerTypes";
-import {
- ReserveTransaction,
- codecForReserveTransaction,
-} from "./ReserveTransaction";
-
-/**
- * Status of a reserve.
- *
- * Schema type for the exchange's response to "/reserve/status".
- */
-export interface ReserveStatus {
- /**
- * Balance left in the reserve.
- */
- balance: AmountString;
-
- /**
- * Transaction history for the reserve.
- */
- history: ReserveTransaction[];
-}
-
-export const codecForReserveStatus = (): Codec<ReserveStatus> =>
- makeCodecForObject<ReserveStatus>()
- .property("balance", codecForString)
- .property("history", makeCodecForList(codecForReserveTransaction()))
- .build("ReserveStatus");
diff --git a/src/types/ReserveTransaction.ts b/src/types/ReserveTransaction.ts
deleted file mode 100644
index bdd9b0f93..000000000
--- a/src/types/ReserveTransaction.ts
+++ /dev/null
@@ -1,250 +0,0 @@
-/*
- 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/>
- */
-
-/**
- * @author Florian Dold <dold@taler.net>
- */
-
-/**
- * Imports.
- */
-import {
- codecForString,
- makeCodecForObject,
- makeCodecForConstString,
- makeCodecForUnion,
- Codec,
-} from "../util/codec";
-import {
- AmountString,
- Base32String,
- EddsaSignatureString,
- EddsaPublicKeyString,
- CoinPublicKeyString,
-} from "./talerTypes";
-import { Timestamp, codecForTimestamp } from "../util/time";
-
-export const enum ReserveTransactionType {
- Withdraw = "WITHDRAW",
- Credit = "CREDIT",
- Recoup = "RECOUP",
- Closing = "CLOSING",
-}
-
-export interface ReserveWithdrawTransaction {
- type: ReserveTransactionType.Withdraw;
-
- /**
- * Amount withdrawn.
- */
- amount: AmountString;
-
- /**
- * Hash of the denomination public key of the coin.
- */
- h_denom_pub: Base32String;
-
- /**
- * Hash of the blinded coin to be signed
- */
- h_coin_envelope: Base32String;
-
- /**
- * Signature of 'TALER_WithdrawRequestPS' created with the reserves's
- * private key.
- */
- reserve_sig: EddsaSignatureString;
-
- /**
- * Fee that is charged for withdraw.
- */
- withdraw_fee: AmountString;
-}
-
-export interface ReserveCreditTransaction {
- type: ReserveTransactionType.Credit;
-
- /**
- * Amount withdrawn.
- */
- amount: AmountString;
-
- /**
- * Sender account payto://-URL
- */
- sender_account_url: string;
-
- /**
- * Transfer details uniquely identifying the transfer.
- */
- wire_reference: string;
-
- /**
- * Timestamp of the incoming wire transfer.
- */
- timestamp: Timestamp;
-}
-
-export interface ReserveClosingTransaction {
- type: ReserveTransactionType.Closing;
-
- /**
- * Closing balance.
- */
- amount: AmountString;
-
- /**
- * Closing fee charged by the exchange.
- */
- closing_fee: AmountString;
-
- /**
- * Wire transfer subject.
- */
- wtid: string;
-
- /**
- * Hash of the wire account into which the funds were returned to.
- */
- h_wire: string;
-
- /**
- * This is a signature over a
- * struct TALER_ReserveCloseConfirmationPS with purpose
- * TALER_SIGNATURE_EXCHANGE_RESERVE_CLOSED.
- */
- exchange_sig: EddsaSignatureString;
-
- /**
- * Public key used to create exchange_sig.
- */
- exchange_pub: EddsaPublicKeyString;
-
- /**
- * Time when the reserve was closed.
- */
- timestamp: Timestamp;
-}
-
-export interface ReserveRecoupTransaction {
- type: ReserveTransactionType.Recoup;
-
- /**
- * Amount paid back.
- */
- amount: AmountString;
-
- /**
- * This is a signature over
- * a struct TALER_PaybackConfirmationPS with purpose
- * TALER_SIGNATURE_EXCHANGE_CONFIRM_PAYBACK.
- */
- exchange_sig: EddsaSignatureString;
-
- /**
- * Public key used to create exchange_sig.
- */
- exchange_pub: EddsaPublicKeyString;
-
- /**
- * Time when the funds were paid back into the reserve.
- */
- timestamp: Timestamp;
-
- /**
- * Public key of the coin that was paid back.
- */
- coin_pub: CoinPublicKeyString;
-}
-
-/**
- * Format of the exchange's transaction history for a reserve.
- */
-export type ReserveTransaction =
- | ReserveWithdrawTransaction
- | ReserveCreditTransaction
- | ReserveClosingTransaction
- | ReserveRecoupTransaction;
-
-export const codecForReserveWithdrawTransaction = (): Codec<
- ReserveWithdrawTransaction
-> =>
- makeCodecForObject<ReserveWithdrawTransaction>()
- .property("amount", codecForString)
- .property("h_coin_envelope", codecForString)
- .property("h_denom_pub", codecForString)
- .property("reserve_sig", codecForString)
- .property("type", makeCodecForConstString(ReserveTransactionType.Withdraw))
- .property("withdraw_fee", codecForString)
- .build("ReserveWithdrawTransaction");
-
-export const codecForReserveCreditTransaction = (): Codec<
- ReserveCreditTransaction
-> =>
- makeCodecForObject<ReserveCreditTransaction>()
- .property("amount", codecForString)
- .property("sender_account_url", codecForString)
- .property("timestamp", codecForTimestamp)
- .property("wire_reference", codecForString)
- .property("type", makeCodecForConstString(ReserveTransactionType.Credit))
- .build("ReserveCreditTransaction");
-
-export const codecForReserveClosingTransaction = (): Codec<
- ReserveClosingTransaction
-> =>
- makeCodecForObject<ReserveClosingTransaction>()
- .property("amount", codecForString)
- .property("closing_fee", codecForString)
- .property("exchange_pub", codecForString)
- .property("exchange_sig", codecForString)
- .property("h_wire", codecForString)
- .property("timestamp", codecForTimestamp)
- .property("type", makeCodecForConstString(ReserveTransactionType.Closing))
- .property("wtid", codecForString)
- .build("ReserveClosingTransaction");
-
-export const codecForReserveRecoupTransaction = (): Codec<
- ReserveRecoupTransaction
-> =>
- makeCodecForObject<ReserveRecoupTransaction>()
- .property("amount", codecForString)
- .property("coin_pub", codecForString)
- .property("exchange_pub", codecForString)
- .property("exchange_sig", codecForString)
- .property("timestamp", codecForTimestamp)
- .property("type", makeCodecForConstString(ReserveTransactionType.Recoup))
- .build("ReserveRecoupTransaction");
-
-export const codecForReserveTransaction = (): Codec<ReserveTransaction> =>
- makeCodecForUnion<ReserveTransaction>()
- .discriminateOn("type")
- .alternative(
- ReserveTransactionType.Withdraw,
- codecForReserveWithdrawTransaction(),
- )
- .alternative(
- ReserveTransactionType.Closing,
- codecForReserveClosingTransaction(),
- )
- .alternative(
- ReserveTransactionType.Recoup,
- codecForReserveRecoupTransaction(),
- )
- .alternative(
- ReserveTransactionType.Credit,
- codecForReserveCreditTransaction(),
- )
- .build<ReserveTransaction>("ReserveTransaction");
diff --git a/src/types/dbTypes.ts b/src/types/dbTypes.ts
deleted file mode 100644
index e03d46417..000000000
--- a/src/types/dbTypes.ts
+++ /dev/null
@@ -1,1818 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2018-2020 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/>
- */
-
-/**
- * Types for records stored in the wallet's database.
- *
- * Types for the objects in the database should end in "-Record".
- */
-
-/**
- * Imports.
- */
-import { AmountJson } from "../util/amounts";
-import {
- Auditor,
- CoinDepositPermission,
- TipResponse,
- ExchangeSignKeyJson,
- MerchantInfo,
- Product,
-} from "./talerTypes";
-
-import { Index, Store } from "../util/query";
-import { OperationErrorDetails, RefreshReason } from "./walletTypes";
-import {
- ReserveTransaction,
- ReserveCreditTransaction,
- ReserveWithdrawTransaction,
- ReserveClosingTransaction,
- ReserveRecoupTransaction,
-} from "./ReserveTransaction";
-import { Timestamp, Duration, getTimestampNow } from "../util/time";
-import { PayCoinSelection, PayCostInfo } from "../operations/pay";
-
-export enum ReserveRecordStatus {
- /**
- * Reserve must be registered with the bank.
- */
- REGISTERING_BANK = "registering-bank",
-
- /**
- * We've registered reserve's information with the bank
- * and are now waiting for the user to confirm the withdraw
- * with the bank (typically 2nd factor auth).
- */
- WAIT_CONFIRM_BANK = "wait-confirm-bank",
-
- /**
- * Querying reserve status with the exchange.
- */
- QUERYING_STATUS = "querying-status",
-
- /**
- * Status is queried, the wallet must now select coins
- * and start withdrawing.
- */
- WITHDRAWING = "withdrawing",
-
- /**
- * The corresponding withdraw record has been created.
- * No further processing is done, unless explicitly requested
- * by the user.
- */
- DORMANT = "dormant",
-}
-
-export interface RetryInfo {
- firstTry: Timestamp;
- nextRetry: Timestamp;
- retryCounter: number;
- active: boolean;
-}
-
-export interface RetryPolicy {
- readonly backoffDelta: Duration;
- readonly backoffBase: number;
-}
-
-const defaultRetryPolicy: RetryPolicy = {
- backoffBase: 1.5,
- backoffDelta: { d_ms: 200 },
-};
-
-export function updateRetryInfoTimeout(
- r: RetryInfo,
- p: RetryPolicy = defaultRetryPolicy,
-): void {
- const now = getTimestampNow();
- if (now.t_ms === "never") {
- throw Error("assertion failed");
- }
- if (p.backoffDelta.d_ms === "forever") {
- r.nextRetry = { t_ms: "never" };
- return;
- }
- const t =
- now.t_ms + p.backoffDelta.d_ms * Math.pow(p.backoffBase, r.retryCounter);
- r.nextRetry = { t_ms: t };
-}
-
-export function initRetryInfo(
- active = true,
- p: RetryPolicy = defaultRetryPolicy,
-): RetryInfo {
- if (!active) {
- return {
- active: false,
- firstTry: { t_ms: Number.MAX_SAFE_INTEGER },
- nextRetry: { t_ms: Number.MAX_SAFE_INTEGER },
- retryCounter: 0,
- };
- }
- const info = {
- firstTry: getTimestampNow(),
- active: true,
- nextRetry: { t_ms: 0 },
- retryCounter: 0,
- };
- updateRetryInfoTimeout(info, p);
- return info;
-}
-
-export const enum WalletReserveHistoryItemType {
- Credit = "credit",
- Withdraw = "withdraw",
- Closing = "closing",
- Recoup = "recoup",
-}
-
-export interface WalletReserveHistoryCreditItem {
- type: WalletReserveHistoryItemType.Credit;
-
- /**
- * Amount we expect to see credited.
- */
- expectedAmount?: AmountJson;
-
- /**
- * Item from the reserve transaction history that this
- * wallet reserve history item matches up with.
- */
- matchedExchangeTransaction?: ReserveCreditTransaction;
-}
-
-export interface WalletReserveHistoryWithdrawItem {
- expectedAmount?: AmountJson;
-
- /**
- * Hash of the blinded coin.
- *
- * When this value is set, it indicates that a withdrawal is active
- * in the wallet for the
- */
- expectedCoinEvHash?: string;
-
- type: WalletReserveHistoryItemType.Withdraw;
-
- /**
- * Item from the reserve transaction history that this
- * wallet reserve history item matches up with.
- */
- matchedExchangeTransaction?: ReserveWithdrawTransaction;
-}
-
-export interface WalletReserveHistoryClosingItem {
- type: WalletReserveHistoryItemType.Closing;
-
- /**
- * Item from the reserve transaction history that this
- * wallet reserve history item matches up with.
- */
- matchedExchangeTransaction?: ReserveClosingTransaction;
-}
-
-export interface WalletReserveHistoryRecoupItem {
- type: WalletReserveHistoryItemType.Recoup;
-
- /**
- * Amount we expect to see recouped.
- */
- expectedAmount?: AmountJson;
-
- /**
- * Item from the reserve transaction history that this
- * wallet reserve history item matches up with.
- */
- matchedExchangeTransaction?: ReserveRecoupTransaction;
-}
-
-export type WalletReserveHistoryItem =
- | WalletReserveHistoryCreditItem
- | WalletReserveHistoryWithdrawItem
- | WalletReserveHistoryRecoupItem
- | WalletReserveHistoryClosingItem;
-
-export interface ReserveHistoryRecord {
- reservePub: string;
- reserveTransactions: WalletReserveHistoryItem[];
-}
-
-export interface ReserveBankInfo {
- /**
- * Status URL that the wallet will use to query the status
- * of the Taler withdrawal operation on the bank's side.
- */
- statusUrl: string;
-
- confirmUrl?: string;
-
- /**
- * Exchange payto URI that the bank will use to fund the reserve.
- */
- exchangePaytoUri: string;
-}
-
-/**
- * A reserve record as stored in the wallet's database.
- */
-export interface ReserveRecord {
- /**
- * The reserve public key.
- */
- reservePub: string;
-
- /**
- * The reserve private key.
- */
- reservePriv: string;
-
- /**
- * The exchange base URL.
- */
- exchangeBaseUrl: string;
-
- /**
- * Currency of the reserve.
- */
- currency: string;
-
- /**
- * Time when the reserve was created.
- */
- timestampCreated: Timestamp;
-
- /**
- * Time when the information about this reserve was posted to the bank.
- *
- * Only applies if bankWithdrawStatusUrl is defined.
- *
- * Set to 0 if that hasn't happened yet.
- */
- timestampReserveInfoPosted: Timestamp | undefined;
-
- /**
- * Time when the reserve was confirmed by the bank.
- *
- * Set to undefined if not confirmed yet.
- */
- timestampBankConfirmed: Timestamp | undefined;
-
- /**
- * Wire information (as payto URI) for the bank account that
- * transfered funds for this reserve.
- */
- senderWire?: string;
-
- /**
- * Amount that was sent by the user to fund the reserve.
- */
- instructedAmount: AmountJson;
-
- /**
- * Extra state for when this is a withdrawal involving
- * a Taler-integrated bank.
- */
- bankInfo?: ReserveBankInfo;
-
- initialWithdrawalGroupId: string;
-
- /**
- * Did we start the first withdrawal for this reserve?
- *
- * We only report a pending withdrawal for the reserve before
- * the first withdrawal has started.
- */
- initialWithdrawalStarted: boolean;
- initialDenomSel: DenomSelectionState;
-
- reserveStatus: ReserveRecordStatus;
-
- /**
- * Time of the last successful status query.
- */
- lastSuccessfulStatusQuery: Timestamp | undefined;
-
- /**
- * Retry info. This field is present even if no retry is scheduled,
- * because we need it to be present for the index on the object store
- * to work.
- */
- retryInfo: RetryInfo;
-
- /**
- * Last error that happened in a reserve operation
- * (either talking to the bank or the exchange).
- */
- lastError: OperationErrorDetails | undefined;
-}
-
-/**
- * Auditor record as stored with currencies in the exchange database.
- */
-export interface AuditorRecord {
- /**
- * Base url of the auditor.
- */
- baseUrl: string;
- /**
- * Public signing key of the auditor.
- */
- auditorPub: string;
- /**
- * Time when the auditing expires.
- */
- expirationStamp: number;
-}
-
-/**
- * Exchange for currencies as stored in the wallet's currency
- * information database.
- */
-export interface ExchangeForCurrencyRecord {
- /**
- * FIXME: unused?
- */
- exchangePub: string;
- /**
- * Base URL of the exchange.
- */
- baseUrl: string;
-}
-
-/**
- * Information about a currency as displayed in the wallet's database.
- */
-export interface CurrencyRecord {
- /**
- * Name of the currency.
- */
- name: string;
- /**
- * Number of fractional digits to show when rendering the currency.
- */
- fractionalDigits: number;
- /**
- * Auditors that the wallet trusts for this currency.
- */
- auditors: AuditorRecord[];
- /**
- * Exchanges that the wallet trusts for this currency.
- */
- exchanges: ExchangeForCurrencyRecord[];
-}
-
-/**
- * Status of a denomination.
- */
-export enum DenominationStatus {
- /**
- * Verification was delayed.
- */
- Unverified,
- /**
- * Verified as valid.
- */
- VerifiedGood,
- /**
- * Verified as invalid.
- */
- VerifiedBad,
-}
-
-/**
- * Denomination record as stored in the wallet's database.
- */
-export interface DenominationRecord {
- /**
- * Value of one coin of the denomination.
- */
- value: AmountJson;
-
- /**
- * The denomination public key.
- */
- denomPub: string;
-
- /**
- * Hash of the denomination public key.
- * Stored in the database for faster lookups.
- */
- denomPubHash: string;
-
- /**
- * Fee for withdrawing.
- */
- feeWithdraw: AmountJson;
-
- /**
- * Fee for depositing.
- */
- feeDeposit: AmountJson;
-
- /**
- * Fee for refreshing.
- */
- feeRefresh: AmountJson;
-
- /**
- * Fee for refunding.
- */
- feeRefund: AmountJson;
-
- /**
- * Validity start date of the denomination.
- */
- stampStart: Timestamp;
-
- /**
- * Date after which the currency can't be withdrawn anymore.
- */
- stampExpireWithdraw: Timestamp;
-
- /**
- * Date after the denomination officially doesn't exist anymore.
- */
- stampExpireLegal: Timestamp;
-
- /**
- * Data after which coins of this denomination can't be deposited anymore.
- */
- stampExpireDeposit: Timestamp;
-
- /**
- * Signature by the exchange's master key over the denomination
- * information.
- */
- masterSig: string;
-
- /**
- * Did we verify the signature on the denomination?
- *
- * FIXME: Rename to "verificationStatus"?
- */
- status: DenominationStatus;
-
- /**
- * Was this denomination still offered by the exchange the last time
- * we checked?
- * Only false when the exchange redacts a previously published denomination.
- */
- isOffered: boolean;
-
- /**
- * Did the exchange revoke the denomination?
- * When this field is set to true in the database, the same transaction
- * should also mark all affected coins as revoked.
- */
- isRevoked: boolean;
-
- /**
- * Base URL of the exchange.
- */
- exchangeBaseUrl: string;
-}
-
-/**
- * Details about the exchange that we only know after
- * querying /keys and /wire.
- */
-export interface ExchangeDetails {
- /**
- * Master public key of the exchange.
- */
- masterPublicKey: string;
-
- /**
- * Auditors (partially) auditing the exchange.
- */
- auditors: Auditor[];
-
- /**
- * Currency that the exchange offers.
- */
- currency: string;
-
- /**
- * Last observed protocol version.
- */
- protocolVersion: string;
-
- /**
- * Signing keys we got from the exchange, can also contain
- * older signing keys that are not returned by /keys anymore.
- */
- signingKeys: ExchangeSignKeyJson[];
-
- /**
- * Timestamp for last update.
- */
- lastUpdateTime: Timestamp;
-}
-
-export const enum ExchangeUpdateStatus {
- FetchKeys = "fetch-keys",
- FetchWire = "fetch-wire",
- FetchTerms = "fetch-terms",
- FinalizeUpdate = "finalize-update",
- Finished = "finished",
-}
-
-export interface ExchangeBankAccount {
- payto_uri: string;
-}
-
-export interface ExchangeWireInfo {
- feesForType: { [wireMethod: string]: WireFee[] };
- accounts: ExchangeBankAccount[];
-}
-
-/**
- * Summary of updates to the exchange.
- */
-// eslint-disable-next-line @typescript-eslint/no-empty-interface
-export interface ExchangeUpdateDiff {
- // FIXME: implement!
-}
-
-export const enum ExchangeUpdateReason {
- Initial = "initial",
- Forced = "forced",
- Scheduled = "scheduled",
-}
-
-/**
- * Exchange record as stored in the wallet's database.
- */
-export interface ExchangeRecord {
- /**
- * Base url of the exchange.
- */
- baseUrl: string;
-
- /**
- * Did we finish adding the exchange?
- */
- addComplete: boolean;
-
- /**
- * Is this a permanent or temporary exchange record?
- */
- permanent: boolean;
-
- /**
- * Was the exchange added as a built-in exchange?
- */
- builtIn: boolean;
-
- /**
- * Details, once known.
- */
- details: ExchangeDetails | undefined;
-
- /**
- * Mapping from wire method type to the wire fee.
- */
- wireInfo: ExchangeWireInfo | undefined;
-
- /**
- * When was the exchange added to the wallet?
- */
- timestampAdded: Timestamp;
-
- /**
- * Terms of service text or undefined if not downloaded yet.
- */
- termsOfServiceText: string | undefined;
-
- /**
- * ETag for last terms of service download.
- */
- termsOfServiceLastEtag: string | undefined;
-
- /**
- * ETag for last terms of service download.
- */
- termsOfServiceAcceptedEtag: string | undefined;
-
- /**
- * ETag for last terms of service download.
- */
- termsOfServiceAcceptedTimestamp: Timestamp | undefined;
-
- /**
- * Time when the update to the exchange has been started or
- * undefined if no update is in progress.
- */
- updateStarted: Timestamp | undefined;
-
- /**
- * Status of updating the info about the exchange.
- */
- updateStatus: ExchangeUpdateStatus;
-
- updateReason?: ExchangeUpdateReason;
-
- /**
- * Update diff, will be incorporated when the update is finalized.
- */
- updateDiff: ExchangeUpdateDiff | undefined;
-
- lastError?: OperationErrorDetails;
-}
-
-/**
- * A coin that isn't yet signed by an exchange.
- */
-export interface PlanchetRecord {
- /**
- * Public key of the coin.
- */
- coinPub: string;
-
- /**
- * Private key of the coin.
- */
- coinPriv: string;
-
- /**
- * Withdrawal group that this planchet belongs to
- * (or the empty string).
- */
- withdrawalGroupId: string;
-
- /**
- * Index within the withdrawal group (or -1).
- */
- coinIdx: number;
-
- withdrawalDone: boolean;
-
- /**
- * Public key of the reserve, this might be a reserve not
- * known to the wallet if the planchet is from a tip.
- */
- reservePub: string;
- denomPubHash: string;
- denomPub: string;
- blindingKey: string;
- withdrawSig: string;
- coinEv: string;
- coinEvHash: string;
- coinValue: AmountJson;
- isFromTip: boolean;
-}
-
-/**
- * Planchet for a coin during refrehs.
- */
-export interface RefreshPlanchetRecord {
- /**
- * Public key for the coin.
- */
- publicKey: string;
- /**
- * Private key for the coin.
- */
- privateKey: string;
- /**
- * Blinded public key.
- */
- coinEv: string;
- /**
- * Blinding key used.
- */
- blindingKey: string;
-}
-
-/**
- * Status of a coin.
- */
-export const enum CoinStatus {
- /**
- * Withdrawn and never shown to anybody.
- */
- Fresh = "fresh",
- /**
- * A coin that has been spent and refreshed.
- */
- Dormant = "dormant",
-}
-
-export const enum CoinSourceType {
- Withdraw = "withdraw",
- Refresh = "refresh",
- Tip = "tip",
-}
-
-export interface WithdrawCoinSource {
- type: CoinSourceType.Withdraw;
- withdrawalGroupId: string;
-
- /**
- * Index of the coin in the withdrawal session.
- */
- coinIndex: number;
-
- /**
- * Reserve public key for the reserve we got this coin from.
- */
- reservePub: string;
-}
-
-export interface RefreshCoinSource {
- type: CoinSourceType.Refresh;
- oldCoinPub: string;
-}
-
-export interface TipCoinSource {
- type: CoinSourceType.Tip;
-}
-
-export type CoinSource = WithdrawCoinSource | RefreshCoinSource | TipCoinSource;
-
-/**
- * CoinRecord as stored in the "coins" data store
- * of the wallet database.
- */
-export interface CoinRecord {
- /**
- * Where did the coin come from? Used for recouping coins.
- */
- coinSource: CoinSource;
-
- /**
- * Public key of the coin.
- */
- coinPub: string;
-
- /**
- * Private key to authorize operations on the coin.
- */
- coinPriv: string;
-
- /**
- * Key used by the exchange used to sign the coin.
- */
- denomPub: string;
-
- /**
- * Hash of the public key that signs the coin.
- */
- denomPubHash: string;
-
- /**
- * Unblinded signature by the exchange.
- */
- denomSig: string;
-
- /**
- * Amount that's left on the coin.
- */
- currentAmount: AmountJson;
-
- /**
- * Base URL that identifies the exchange from which we got the
- * coin.
- */
- exchangeBaseUrl: string;
-
- /**
- * The coin is currently suspended, and will not be used for payments.
- */
- suspended: boolean;
-
- /**
- * Blinding key used when withdrawing the coin.
- * Potentionally sed again during payback.
- */
- blindingKey: string;
-
- /**
- * Status of the coin.
- */
- status: CoinStatus;
-}
-
-export const enum ProposalStatus {
- /**
- * Not downloaded yet.
- */
- DOWNLOADING = "downloading",
- /**
- * Proposal downloaded, but the user needs to accept/reject it.
- */
- PROPOSED = "proposed",
- /**
- * The user has accepted the proposal.
- */
- ACCEPTED = "accepted",
- /**
- * The user has rejected the proposal.
- */
- REFUSED = "refused",
- /**
- * Downloaded proposal was detected as a re-purchase.
- */
- REPURCHASE = "repurchase",
-}
-
-export interface ProposalDownload {
- /**
- * The contract that was offered by the merchant.
- */
- contractTermsRaw: string;
-
- contractData: WalletContractData;
-}
-
-/**
- * Record for a downloaded order, stored in the wallet's database.
- */
-export interface ProposalRecord {
- orderId: string;
-
- merchantBaseUrl: string;
-
- /**
- * Downloaded data from the merchant.
- */
- download: ProposalDownload | undefined;
-
- /**
- * Unique ID when the order is stored in the wallet DB.
- */
- proposalId: string;
-
- /**
- * Timestamp (in ms) of when the record
- * was created.
- */
- timestamp: Timestamp;
-
- /**
- * Private key for the nonce.
- */
- noncePriv: string;
-
- /**
- * Public key for the nonce.
- */
- noncePub: string;
-
- claimToken: string | undefined;
-
- proposalStatus: ProposalStatus;
-
- repurchaseProposalId: string | undefined;
-
- /**
- * Session ID we got when downloading the contract.
- */
- downloadSessionId?: string;
-
- /**
- * Retry info, even present when the operation isn't active to allow indexing
- * on the next retry timestamp.
- */
- retryInfo: RetryInfo;
-
- lastError: OperationErrorDetails | undefined;
-}
-
-/**
- * Status of a tip we got from a merchant.
- */
-export interface TipRecord {
- lastError: OperationErrorDetails | undefined;
-
- /**
- * Has the user accepted the tip? Only after the tip has been accepted coins
- * withdrawn from the tip may be used.
- */
- acceptedTimestamp: Timestamp | undefined;
-
- /**
- * Has the user rejected the tip?
- */
- rejectedTimestamp: Timestamp | undefined;
-
- /**
- * Have we picked up the tip record from the merchant already?
- */
- pickedUp: boolean;
-
- /**
- * The tipped amount.
- */
- amount: AmountJson;
-
- totalFees: AmountJson;
-
- /**
- * Timestamp, the tip can't be picked up anymore after this deadline.
- */
- deadline: Timestamp;
-
- /**
- * The exchange that will sign our coins, chosen by the merchant.
- */
- exchangeUrl: string;
-
- /**
- * Base URL of the merchant that is giving us the tip.
- */
- merchantBaseUrl: string;
-
- /**
- * Planchets, the members included in TipPlanchetDetail will be sent to the
- * merchant.
- */
- planchets?: TipPlanchet[];
-
- denomsSel: DenomSelectionState;
-
- /**
- * Response if the merchant responded,
- * undefined otherwise.
- */
- response?: TipResponse[];
-
- /**
- * Tip ID chosen by the wallet.
- */
- tipId: string;
-
- /**
- * The merchant's identifier for this tip.
- */
- merchantTipId: string;
-
- /**
- * URL to go to once the tip has been accepted.
- */
- nextUrl?: string;
-
- createdTimestamp: Timestamp;
-
- /**
- * Retry info, even present when the operation isn't active to allow indexing
- * on the next retry timestamp.
- */
- retryInfo: RetryInfo;
-}
-
-export interface RefreshGroupRecord {
- /**
- * Retry info, even present when the operation isn't active to allow indexing
- * on the next retry timestamp.
- */
- retryInfo: RetryInfo;
-
- lastError: OperationErrorDetails | undefined;
-
- lastErrorPerCoin: { [coinIndex: number]: OperationErrorDetails };
-
- refreshGroupId: string;
-
- reason: RefreshReason;
-
- oldCoinPubs: string[];
-
- refreshSessionPerCoin: (RefreshSessionRecord | undefined)[];
-
- /**
- * Flag for each coin whether refreshing finished.
- * If a coin can't be refreshed (remaining value too small),
- * it will be marked as finished, but no refresh session will
- * be created.
- */
- finishedPerCoin: boolean[];
-
- /**
- * Timestamp when the refresh session finished.
- */
- timestampFinished: Timestamp | undefined;
-}
-
-/**
- * Ongoing refresh
- */
-export interface RefreshSessionRecord {
- lastError: OperationErrorDetails | undefined;
-
- /**
- * Public key that's being melted in this session.
- */
- meltCoinPub: string;
-
- /**
- * How much of the coin's value is melted away
- * with this refresh session?
- */
- amountRefreshInput: AmountJson;
-
- /**
- * Sum of the value of denominations we want
- * to withdraw in this session, without fees.
- */
- amountRefreshOutput: AmountJson;
-
- /**
- * Signature to confirm the melting.
- */
- confirmSig: string;
-
- /**
- * Hased denominations of the newly requested coins.
- */
- newDenomHashes: string[];
-
- /**
- * Denominations of the newly requested coins.
- */
- newDenoms: string[];
-
- /**
- * Planchets for each cut-and-choose instance.
- */
- planchetsForGammas: RefreshPlanchetRecord[][];
-
- /**
- * The transfer keys, kappa of them.
- */
- transferPubs: string[];
-
- /**
- * Private keys for the transfer public keys.
- */
- transferPrivs: string[];
-
- /**
- * The no-reveal-index after we've done the melting.
- */
- norevealIndex?: number;
-
- /**
- * Hash of the session.
- */
- hash: string;
-
- /**
- * Timestamp when the refresh session finished.
- */
- finishedTimestamp: Timestamp | undefined;
-
- /**
- * When has this refresh session been created?
- */
- timestampCreated: Timestamp;
-
- /**
- * Base URL for the exchange we're doing the refresh with.
- */
- exchangeBaseUrl: string;
-}
-
-/**
- * Tipping planchet stored in the database.
- */
-export interface TipPlanchet {
- blindingKey: string;
- coinEv: string;
- coinPriv: string;
- coinPub: string;
- coinValue: AmountJson;
- denomPubHash: string;
- denomPub: string;
-}
-
-/**
- * Wire fee for one wire method as stored in the
- * wallet's database.
- */
-export interface WireFee {
- /**
- * Fee for wire transfers.
- */
- wireFee: AmountJson;
-
- /**
- * Fees to close and refund a reserve.
- */
- closingFee: AmountJson;
-
- /**
- * Start date of the fee.
- */
- startStamp: Timestamp;
-
- /**
- * End date of the fee.
- */
- endStamp: Timestamp;
-
- /**
- * Signature made by the exchange master key.
- */
- sig: string;
-}
-
-/**
- * Record to store information about a refund event.
- *
- * All information about a refund is stored with the purchase,
- * this event is just for the history.
- *
- * The event is only present for completed refunds.
- */
-export interface RefundEventRecord {
- timestamp: Timestamp;
- merchantExecutionTimestamp: Timestamp;
- refundGroupId: string;
- proposalId: string;
-}
-
-export const enum RefundState {
- Failed = "failed",
- Applied = "applied",
- Pending = "pending",
-}
-
-/**
- * State of one refund from the merchant, maintained by the wallet.
- */
-export type WalletRefundItem =
- | WalletRefundFailedItem
- | WalletRefundPendingItem
- | WalletRefundAppliedItem;
-
-export interface WalletRefundItemCommon {
- executionTime: Timestamp;
- refundAmount: AmountJson;
- refundFee: AmountJson;
-
- /**
- * Upper bound on the refresh cost incurred by
- * applying this refund.
- *
- * Might be lower in practice when two refunds on the same
- * coin are refreshed in the same refresh operation.
- */
- totalRefreshCostBound: AmountJson;
-}
-
-/**
- * Failed refund, either because the merchant did
- * something wrong or it expired.
- */
-export interface WalletRefundFailedItem extends WalletRefundItemCommon {
- type: RefundState.Failed;
-}
-
-export interface WalletRefundPendingItem extends WalletRefundItemCommon {
- type: RefundState.Pending;
-}
-
-export interface WalletRefundAppliedItem extends WalletRefundItemCommon {
- type: RefundState.Applied;
-}
-
-export const enum RefundReason {
- /**
- * Normal refund given by the merchant.
- */
- NormalRefund = "normal-refund",
- /**
- * Refund from an aborted payment.
- */
- AbortRefund = "abort-pay-refund",
-}
-
-/**
- * Record stored for every time we successfully submitted
- * a payment to the merchant (both first time and re-play).
- */
-export interface PayEventRecord {
- proposalId: string;
- sessionId: string | undefined;
- isReplay: boolean;
- timestamp: Timestamp;
-}
-
-export interface ExchangeUpdatedEventRecord {
- exchangeBaseUrl: string;
- timestamp: Timestamp;
-}
-
-export interface ReserveUpdatedEventRecord {
- amountReserveBalance: string;
- amountExpected: string;
- reservePub: string;
- timestamp: Timestamp;
- reserveUpdateId: string;
- newHistoryTransactions: ReserveTransaction[];
-}
-
-export interface AllowedAuditorInfo {
- auditorBaseUrl: string;
- auditorPub: string;
-}
-
-export interface AllowedExchangeInfo {
- exchangeBaseUrl: string;
- exchangePub: string;
-}
-
-/**
- * Data extracted from the contract terms that is relevant for payment
- * processing in the wallet.
- */
-export interface WalletContractData {
- products?: Product[];
- summaryI18n: { [lang_tag: string]: string } | undefined;
- fulfillmentUrl: string;
- contractTermsHash: string;
- merchantSig: string;
- merchantPub: string;
- merchant: MerchantInfo;
- amount: AmountJson;
- orderId: string;
- merchantBaseUrl: string;
- summary: string;
- autoRefund: Duration | undefined;
- maxWireFee: AmountJson;
- wireFeeAmortization: number;
- payDeadline: Timestamp;
- refundDeadline: Timestamp;
- allowedAuditors: AllowedAuditorInfo[];
- allowedExchanges: AllowedExchangeInfo[];
- timestamp: Timestamp;
- wireMethod: string;
- wireInfoHash: string;
- maxDepositFee: AmountJson;
-}
-
-/**
- * Record that stores status information about one purchase, starting from when
- * the customer accepts a proposal. Includes refund status if applicable.
- */
-export interface PurchaseRecord {
- /**
- * Proposal ID for this purchase. Uniquely identifies the
- * purchase and the proposal.
- */
- proposalId: string;
-
- /**
- * Contract terms we got from the merchant.
- */
- contractTermsRaw: string;
-
- contractData: WalletContractData;
-
- /**
- * Deposit permissions, available once the user has accepted the payment.
- */
- coinDepositPermissions: CoinDepositPermission[];
-
- payCoinSelection: PayCoinSelection;
-
- payCostInfo: PayCostInfo;
-
- /**
- * Timestamp of the first time that sending a payment to the merchant
- * for this purchase was successful.
- */
- timestampFirstSuccessfulPay: Timestamp | undefined;
-
- /**
- * When was the purchase made?
- * Refers to the time that the user accepted.
- */
- timestampAccept: Timestamp;
-
- /**
- * Pending refunds for the purchase. A refund is pending
- * when the merchant reports a transient error from the exchange.
- */
- refunds: { [refundKey: string]: WalletRefundItem };
-
- /**
- * When was the last refund made?
- * Set to 0 if no refund was made on the purchase.
- */
- timestampLastRefundStatus: Timestamp | undefined;
-
- /**
- * Last session signature that we submitted to /pay (if any).
- */
- lastSessionId: string | undefined;
-
- /**
- * Set for the first payment, or on re-plays.
- */
- paymentSubmitPending: boolean;
-
- /**
- * Do we need to query the merchant for the refund status
- * of the payment?
- */
- refundStatusRequested: boolean;
-
- /**
- * An abort (with refund) was requested for this (incomplete!) purchase.
- */
- abortRequested: boolean;
-
- /**
- * The abort (with refund) was completed for this (incomplete!) purchase.
- */
- abortDone: boolean;
-
- payRetryInfo: RetryInfo;
-
- lastPayError: OperationErrorDetails | undefined;
-
- /**
- * Retry information for querying the refund status with the merchant.
- */
- refundStatusRetryInfo: RetryInfo;
-
- /**
- * Last error (or undefined) for querying the refund status with the merchant.
- */
- lastRefundStatusError: OperationErrorDetails | undefined;
-
- /**
- * Continue querying the refund status until this deadline has expired.
- */
- autoRefundDeadline: Timestamp | undefined;
-}
-
-/**
- * Information about wire information for bank accounts we withdrew coins from.
- */
-export interface SenderWireRecord {
- paytoUri: string;
-}
-
-/**
- * Configuration key/value entries to configure
- * the wallet.
- */
-export interface ConfigRecord {
- key: string;
- value: any;
-}
-
-/**
- * Coin that we're depositing ourselves.
- */
-export interface DepositCoin {
- coinPaySig: CoinDepositPermission;
-
- /**
- * Undefined if coin not deposited, otherwise signature
- * from the exchange confirming the deposit.
- */
- depositedSig?: string;
-}
-
-/**
- * Record stored in the wallet's database when the user sends coins back to
- * their own bank account. Stores the status of coins that are deposited to
- * the wallet itself, where the wallet acts as a "merchant" for the customer.
- */
-export interface CoinsReturnRecord {
- contractTermsRaw: string;
-
- contractData: WalletContractData;
-
- /**
- * Private key where corresponding
- * public key is used in the contract terms
- * as merchant pub.
- */
- merchantPriv: string;
-
- coins: DepositCoin[];
-
- /**
- * Exchange base URL to deposit coins at.
- */
- exchange: string;
-
- /**
- * Our own wire information for the deposit.
- */
- wire: any;
-}
-
-export const enum WithdrawalSourceType {
- Tip = "tip",
- Reserve = "reserve",
-}
-
-export interface WithdrawalSourceTip {
- type: WithdrawalSourceType.Tip;
- tipId: string;
-}
-
-export interface WithdrawalSourceReserve {
- type: WithdrawalSourceType.Reserve;
- reservePub: string;
-}
-
-export type WithdrawalSource = WithdrawalSourceTip | WithdrawalSourceReserve;
-
-export interface DenominationSelectionInfo {
- totalCoinValue: AmountJson;
- totalWithdrawCost: AmountJson;
- selectedDenoms: {
- /**
- * How many times do we withdraw this denomination?
- */
- count: number;
- denom: DenominationRecord;
- }[];
-}
-
-export interface DenomSelectionState {
- totalCoinValue: AmountJson;
- totalWithdrawCost: AmountJson;
- selectedDenoms: {
- denomPubHash: string;
- count: number;
- }[];
-}
-
-/**
- * Group of withdrawal operations that need to be executed.
- * (Either for a normal withdrawal or from a tip.)
- *
- * The withdrawal group record is only created after we know
- * the coin selection we want to withdraw.
- */
-export interface WithdrawalGroupRecord {
- withdrawalGroupId: string;
-
- /**
- * Withdrawal source. Fields that don't apply to the respective
- * withdrawal source type must be null (i.e. can't be absent),
- * otherwise the IndexedDB indexing won't like us.
- */
- source: WithdrawalSource;
-
- exchangeBaseUrl: string;
-
- /**
- * When was the withdrawal operation started started?
- * Timestamp in milliseconds.
- */
- timestampStart: Timestamp;
-
- /**
- * When was the withdrawal operation completed?
- */
- timestampFinish?: Timestamp;
-
- /**
- * Amount including fees (i.e. the amount subtracted from the
- * reserve to withdraw all coins in this withdrawal session).
- */
- rawWithdrawalAmount: AmountJson;
-
- denomsSel: DenomSelectionState;
-
- /**
- * Retry info, always present even on completed operations so that indexing works.
- */
- retryInfo: RetryInfo;
-
- /**
- * Last error per coin/planchet, or undefined if no error occured for
- * the coin/planchet.
- */
- lastErrorPerCoin: { [coinIndex: number]: OperationErrorDetails };
-
- lastError: OperationErrorDetails | undefined;
-}
-
-export interface BankWithdrawUriRecord {
- /**
- * The withdraw URI we got from the bank.
- */
- talerWithdrawUri: string;
-
- /**
- * Reserve that was created for the withdraw URI.
- */
- reservePub: string;
-}
-
-/**
- * Status of recoup operations that were grouped together.
- *
- * The remaining amount of involved coins should be set to zero
- * in the same transaction that inserts the RecoupGroupRecord.
- */
-export interface RecoupGroupRecord {
- /**
- * Unique identifier for the recoup group record.
- */
- recoupGroupId: string;
-
- timestampStarted: Timestamp;
-
- timestampFinished: Timestamp | undefined;
-
- /**
- * Public keys that identify the coins being recouped
- * as part of this session.
- *
- * (Structured like this to enable multiEntry indexing in IndexedDB.)
- */
- coinPubs: string[];
-
- /**
- * Array of flags to indicate whether the recoup finished on each individual coin.
- */
- recoupFinishedPerCoin: boolean[];
-
- /**
- * We store old amount (i.e. before recoup) of recouped coins here,
- * as the balance of a recouped coin is set to zero when the
- * recoup group is created.
- */
- oldAmountPerCoin: AmountJson[];
-
- /**
- * Public keys of coins that should be scheduled for refreshing
- * after all individual recoups are done.
- */
- scheduleRefreshCoins: string[];
-
- /**
- * Retry info.
- */
- retryInfo: RetryInfo;
-
- /**
- * Last error that occured, if any.
- */
- lastError: OperationErrorDetails | undefined;
-}
-
-export const enum ImportPayloadType {
- CoreSchema = "core-schema",
-}
-
-/**
- * Record to keep track of data imported into the wallet.
- */
-export class WalletImportRecord {
- /**
- * Unique ID to reference this import record.
- */
- walletImportId: string;
-
- /**
- * When was the data imported?
- */
- timestampImportStarted: Timestamp;
-
- timestampImportFinished: Timestamp | undefined;
-
- payloadType: ImportPayloadType;
-
- /**
- * The actual data to import.
- */
- payload: any;
-}
-
-/* tslint:disable:completed-docs */
-
-/**
- * The stores and indices for the wallet database.
- */
-// eslint-disable-next-line @typescript-eslint/no-namespace
-export namespace Stores {
- class ExchangesStore extends Store<ExchangeRecord> {
- constructor() {
- super("exchanges", { keyPath: "baseUrl" });
- }
- }
-
- class CoinsStore extends Store<CoinRecord> {
- constructor() {
- super("coins", { keyPath: "coinPub" });
- }
-
- exchangeBaseUrlIndex = new Index<string, CoinRecord>(
- this,
- "exchangeBaseUrl",
- "exchangeBaseUrl",
- );
- denomPubIndex = new Index<string, CoinRecord>(
- this,
- "denomPubIndex",
- "denomPub",
- );
- denomPubHashIndex = new Index<string, CoinRecord>(
- this,
- "denomPubHashIndex",
- "denomPubHash",
- );
- }
-
- class ProposalsStore extends Store<ProposalRecord> {
- constructor() {
- super("proposals", { keyPath: "proposalId" });
- }
- urlAndOrderIdIndex = new Index<string, ProposalRecord>(this, "urlIndex", [
- "merchantBaseUrl",
- "orderId",
- ]);
- }
-
- class PurchasesStore extends Store<PurchaseRecord> {
- constructor() {
- super("purchases", { keyPath: "proposalId" });
- }
-
- fulfillmentUrlIndex = new Index<string, PurchaseRecord>(
- this,
- "fulfillmentUrlIndex",
- "contractData.fulfillmentUrl",
- );
- orderIdIndex = new Index<string, PurchaseRecord>(this, "orderIdIndex", [
- "contractData.merchantBaseUrl",
- "contractData.orderId",
- ]);
- }
-
- class DenominationsStore extends Store<DenominationRecord> {
- constructor() {
- // cast needed because of bug in type annotations
- super("denominations", {
- keyPath: (["exchangeBaseUrl", "denomPub"] as any) as IDBKeyPath,
- });
- }
-
- denomPubHashIndex = new Index<string, DenominationRecord>(
- this,
- "denomPubHashIndex",
- "denomPubHash",
- );
- exchangeBaseUrlIndex = new Index<string, DenominationRecord>(
- this,
- "exchangeBaseUrlIndex",
- "exchangeBaseUrl",
- );
- denomPubIndex = new Index<string, DenominationRecord>(
- this,
- "denomPubIndex",
- "denomPub",
- );
- }
-
- class CurrenciesStore extends Store<CurrencyRecord> {
- constructor() {
- super("currencies", { keyPath: "name" });
- }
- }
-
- class ConfigStore extends Store<ConfigRecord> {
- constructor() {
- super("config", { keyPath: "key" });
- }
- }
-
- class ReservesStore extends Store<ReserveRecord> {
- constructor() {
- super("reserves", { keyPath: "reservePub" });
- }
- }
-
- class ReserveHistoryStore extends Store<ReserveHistoryRecord> {
- constructor() {
- super("reserveHistory", { keyPath: "reservePub" });
- }
- }
-
- class TipsStore extends Store<TipRecord> {
- constructor() {
- super("tips", { keyPath: "tipId" });
- }
- }
-
- class SenderWiresStore extends Store<SenderWireRecord> {
- constructor() {
- super("senderWires", { keyPath: "paytoUri" });
- }
- }
-
- class WithdrawalGroupsStore extends Store<WithdrawalGroupRecord> {
- constructor() {
- super("withdrawals", { keyPath: "withdrawalGroupId" });
- }
- }
-
- class PlanchetsStore extends Store<PlanchetRecord> {
- constructor() {
- super("planchets", { keyPath: "coinPub" });
- }
- byGroupAndIndex = new Index<string, PlanchetRecord>(
- this,
- "withdrawalGroupAndCoinIdxIndex",
- ["withdrawalGroupId", "coinIdx"],
- );
- byGroup = new Index<string, PlanchetRecord>(
- this,
- "withdrawalGroupIndex",
- "withdrawalGroupId",
- );
- }
-
- class RefundEventsStore extends Store<RefundEventRecord> {
- constructor() {
- super("refundEvents", { keyPath: "refundGroupId" });
- }
- }
-
- class PayEventsStore extends Store<PayEventRecord> {
- constructor() {
- super("payEvents", { keyPath: "proposalId" });
- }
- }
-
- class ExchangeUpdatedEventsStore extends Store<ExchangeUpdatedEventRecord> {
- constructor() {
- super("exchangeUpdatedEvents", { keyPath: "exchangeBaseUrl" });
- }
- }
-
- class ReserveUpdatedEventsStore extends Store<ReserveUpdatedEventRecord> {
- constructor() {
- super("reserveUpdatedEvents", { keyPath: "reservePub" });
- }
- }
-
- class BankWithdrawUrisStore extends Store<BankWithdrawUriRecord> {
- constructor() {
- super("bankWithdrawUris", { keyPath: "talerWithdrawUri" });
- }
- }
-
- class WalletImportsStore extends Store<WalletImportRecord> {
- constructor() {
- super("walletImports", { keyPath: "walletImportId" });
- }
- }
-
- export const coins = new CoinsStore();
- export const coinsReturns = new Store<CoinsReturnRecord>("coinsReturns", {
- keyPath: "contractTermsHash",
- });
- export const config = new ConfigStore();
- export const currencies = new CurrenciesStore();
- export const denominations = new DenominationsStore();
- export const exchanges = new ExchangesStore();
- export const proposals = new ProposalsStore();
- export const refreshGroups = new Store<RefreshGroupRecord>("refreshGroups", {
- keyPath: "refreshGroupId",
- });
- export const recoupGroups = new Store<RecoupGroupRecord>("recoupGroups", {
- keyPath: "recoupGroupId",
- });
- export const reserves = new ReservesStore();
- export const reserveHistory = new ReserveHistoryStore();
- export const purchases = new PurchasesStore();
- export const tips = new TipsStore();
- export const senderWires = new SenderWiresStore();
- export const withdrawalGroups = new WithdrawalGroupsStore();
- export const planchets = new PlanchetsStore();
- export const bankWithdrawUris = new BankWithdrawUrisStore();
- export const refundEvents = new RefundEventsStore();
- export const payEvents = new PayEventsStore();
- export const reserveUpdatedEvents = new ReserveUpdatedEventsStore();
- export const exchangeUpdatedEvents = new ExchangeUpdatedEventsStore();
- export const walletImports = new WalletImportsStore();
-}
-
-/* tslint:enable:completed-docs */
diff --git a/src/types/notifications.ts b/src/types/notifications.ts
deleted file mode 100644
index 945b86eea..000000000
--- a/src/types/notifications.ts
+++ /dev/null
@@ -1,255 +0,0 @@
-/*
- 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/>
- */
-
-/**
- * Type and schema definitions for notifications from the wallet to clients
- * of the wallet.
- */
-
-/**
- * Imports.
- */
-import { OperationErrorDetails } from "./walletTypes";
-import { WithdrawalSource } from "./dbTypes";
-
-export const enum NotificationType {
- CoinWithdrawn = "coin-withdrawn",
- ProposalAccepted = "proposal-accepted",
- ProposalDownloaded = "proposal-downloaded",
- RefundsSubmitted = "refunds-submitted",
- RecoupStarted = "recoup-started",
- RecoupFinished = "recoup-finished",
- RefreshRevealed = "refresh-revealed",
- RefreshMelted = "refresh-melted",
- RefreshStarted = "refresh-started",
- RefreshUnwarranted = "refresh-unwarranted",
- ReserveUpdated = "reserve-updated",
- ReserveConfirmed = "reserve-confirmed",
- ReserveCreated = "reserve-created",
- WithdrawGroupCreated = "withdraw-group-created",
- WithdrawGroupFinished = "withdraw-group-finished",
- WaitingForRetry = "waiting-for-retry",
- RefundStarted = "refund-started",
- RefundQueried = "refund-queried",
- RefundFinished = "refund-finished",
- ExchangeOperationError = "exchange-operation-error",
- RefreshOperationError = "refresh-operation-error",
- RecoupOperationError = "recoup-operation-error",
- RefundApplyOperationError = "refund-apply-error",
- RefundStatusOperationError = "refund-status-error",
- ProposalOperationError = "proposal-error",
- TipOperationError = "tip-error",
- PayOperationError = "pay-error",
- WithdrawOperationError = "withdraw-error",
- ReserveNotYetFound = "reserve-not-yet-found",
- ReserveOperationError = "reserve-error",
- InternalError = "internal-error",
- PendingOperationProcessed = "pending-operation-processed",
- ProposalRefused = "proposal-refused",
- ReserveRegisteredWithBank = "reserve-registered-with-bank",
-}
-
-export interface ProposalAcceptedNotification {
- type: NotificationType.ProposalAccepted;
- proposalId: string;
-}
-
-export interface InternalErrorNotification {
- type: NotificationType.InternalError;
- message: string;
- exception: any;
-}
-
-export interface ReserveNotYetFoundNotification {
- type: NotificationType.ReserveNotYetFound;
- reservePub: string;
-}
-
-export interface CoinWithdrawnNotification {
- type: NotificationType.CoinWithdrawn;
-}
-
-export interface RefundStartedNotification {
- type: NotificationType.RefundStarted;
-}
-
-export interface RefundQueriedNotification {
- type: NotificationType.RefundQueried;
-}
-
-export interface ProposalDownloadedNotification {
- type: NotificationType.ProposalDownloaded;
- proposalId: string;
-}
-
-export interface RefundsSubmittedNotification {
- type: NotificationType.RefundsSubmitted;
- proposalId: string;
-}
-
-export interface RecoupStartedNotification {
- type: NotificationType.RecoupStarted;
-}
-
-export interface RecoupFinishedNotification {
- type: NotificationType.RecoupFinished;
-}
-
-export interface RefreshMeltedNotification {
- type: NotificationType.RefreshMelted;
-}
-
-export interface RefreshRevealedNotification {
- type: NotificationType.RefreshRevealed;
-}
-
-export interface RefreshStartedNotification {
- type: NotificationType.RefreshStarted;
-}
-
-export interface RefreshRefusedNotification {
- type: NotificationType.RefreshUnwarranted;
-}
-
-export interface ReserveUpdatedNotification {
- type: NotificationType.ReserveUpdated;
-}
-
-export interface ReserveConfirmedNotification {
- type: NotificationType.ReserveConfirmed;
-}
-
-export interface WithdrawalGroupCreatedNotification {
- type: NotificationType.WithdrawGroupCreated;
- withdrawalGroupId: string;
-}
-
-export interface WithdrawalGroupFinishedNotification {
- type: NotificationType.WithdrawGroupFinished;
- withdrawalSource: WithdrawalSource;
-}
-
-export interface WaitingForRetryNotification {
- type: NotificationType.WaitingForRetry;
- numPending: number;
- numGivingLiveness: number;
-}
-
-export interface RefundFinishedNotification {
- type: NotificationType.RefundFinished;
-}
-
-export interface ExchangeOperationErrorNotification {
- type: NotificationType.ExchangeOperationError;
- error: OperationErrorDetails;
-}
-
-export interface RefreshOperationErrorNotification {
- type: NotificationType.RefreshOperationError;
- error: OperationErrorDetails;
-}
-
-export interface RefundStatusOperationErrorNotification {
- type: NotificationType.RefundStatusOperationError;
- error: OperationErrorDetails;
-}
-
-export interface RefundApplyOperationErrorNotification {
- type: NotificationType.RefundApplyOperationError;
- error: OperationErrorDetails;
-}
-
-export interface PayOperationErrorNotification {
- type: NotificationType.PayOperationError;
- error: OperationErrorDetails;
-}
-
-export interface ProposalOperationErrorNotification {
- type: NotificationType.ProposalOperationError;
- error: OperationErrorDetails;
-}
-
-export interface TipOperationErrorNotification {
- type: NotificationType.TipOperationError;
-}
-
-export interface WithdrawOperationErrorNotification {
- type: NotificationType.WithdrawOperationError;
- error: OperationErrorDetails;
-}
-
-export interface RecoupOperationErrorNotification {
- type: NotificationType.RecoupOperationError;
- error: OperationErrorDetails;
-}
-
-export interface ReserveOperationErrorNotification {
- type: NotificationType.ReserveOperationError;
- error: OperationErrorDetails;
-}
-
-export interface ReserveCreatedNotification {
- type: NotificationType.ReserveCreated;
- reservePub: string;
-}
-
-export interface PendingOperationProcessedNotification {
- type: NotificationType.PendingOperationProcessed;
-}
-
-export interface ProposalRefusedNotification {
- type: NotificationType.ProposalRefused;
-}
-
-export interface ReserveRegisteredWithBankNotification {
- type: NotificationType.ReserveRegisteredWithBank;
-}
-
-export type WalletNotification =
- | WithdrawOperationErrorNotification
- | ReserveOperationErrorNotification
- | ExchangeOperationErrorNotification
- | RefreshOperationErrorNotification
- | RefundStatusOperationErrorNotification
- | RefundApplyOperationErrorNotification
- | ProposalOperationErrorNotification
- | PayOperationErrorNotification
- | TipOperationErrorNotification
- | ProposalAcceptedNotification
- | ProposalDownloadedNotification
- | RefundsSubmittedNotification
- | RecoupStartedNotification
- | RecoupFinishedNotification
- | RefreshMeltedNotification
- | RefreshRevealedNotification
- | RefreshStartedNotification
- | RefreshRefusedNotification
- | ReserveUpdatedNotification
- | ReserveCreatedNotification
- | ReserveConfirmedNotification
- | WithdrawalGroupFinishedNotification
- | WaitingForRetryNotification
- | RefundStartedNotification
- | RefundFinishedNotification
- | RefundQueriedNotification
- | WithdrawalGroupCreatedNotification
- | CoinWithdrawnNotification
- | RecoupOperationErrorNotification
- | InternalErrorNotification
- | PendingOperationProcessedNotification
- | ProposalRefusedNotification
- | ReserveRegisteredWithBankNotification
- | ReserveNotYetFoundNotification;
diff --git a/src/types/pending.ts b/src/types/pending.ts
deleted file mode 100644
index 85f7585c5..000000000
--- a/src/types/pending.ts
+++ /dev/null
@@ -1,258 +0,0 @@
-/*
- 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/>
- */
-
-/**
- * Type and schema definitions for pending operations in the wallet.
- */
-
-/**
- * Imports.
- */
-import { OperationErrorDetails, BalancesResponse } from "./walletTypes";
-import { WithdrawalSource, RetryInfo, ReserveRecordStatus } from "./dbTypes";
-import { Timestamp, Duration } from "../util/time";
-
-export const enum PendingOperationType {
- Bug = "bug",
- ExchangeUpdate = "exchange-update",
- Pay = "pay",
- ProposalChoice = "proposal-choice",
- ProposalDownload = "proposal-download",
- Refresh = "refresh",
- Reserve = "reserve",
- Recoup = "recoup",
- RefundQuery = "refund-query",
- TipChoice = "tip-choice",
- TipPickup = "tip-pickup",
- Withdraw = "withdraw",
-}
-
-/**
- * Information about a pending operation.
- */
-export type PendingOperationInfo = PendingOperationInfoCommon &
- (
- | PendingBugOperation
- | PendingExchangeUpdateOperation
- | PendingPayOperation
- | PendingProposalChoiceOperation
- | PendingProposalDownloadOperation
- | PendingRefreshOperation
- | PendingRefundQueryOperation
- | PendingReserveOperation
- | PendingTipChoiceOperation
- | PendingTipPickupOperation
- | PendingWithdrawOperation
- | PendingRecoupOperation
- );
-
-/**
- * The wallet is currently updating information about an exchange.
- */
-export interface PendingExchangeUpdateOperation {
- type: PendingOperationType.ExchangeUpdate;
- stage: ExchangeUpdateOperationStage;
- reason: string;
- exchangeBaseUrl: string;
- lastError: OperationErrorDetails | undefined;
-}
-
-/**
- * Some interal error happened in the wallet. This pending operation
- * should *only* be reported for problems in the wallet, not when
- * a problem with a merchant/exchange/etc. occurs.
- */
-export interface PendingBugOperation {
- type: PendingOperationType.Bug;
- message: string;
- details: any;
-}
-
-/**
- * Current state of an exchange update operation.
- */
-export const enum ExchangeUpdateOperationStage {
- FetchKeys = "fetch-keys",
- FetchWire = "fetch-wire",
- FinalizeUpdate = "finalize-update",
-}
-
-export const enum ReserveType {
- /**
- * Manually created.
- */
- Manual = "manual",
- /**
- * Withdrawn from a bank that has "tight" Taler integration
- */
- TalerBankWithdraw = "taler-bank-withdraw",
-}
-
-/**
- * Status of processing a reserve.
- *
- * Does *not* include the withdrawal operation that might result
- * from this.
- */
-export interface PendingReserveOperation {
- type: PendingOperationType.Reserve;
- retryInfo: RetryInfo | undefined;
- stage: ReserveRecordStatus;
- timestampCreated: Timestamp;
- reserveType: ReserveType;
- reservePub: string;
- bankWithdrawConfirmUrl?: string;
-}
-
-/**
- * Status of an ongoing withdrawal operation.
- */
-export interface PendingRefreshOperation {
- type: PendingOperationType.Refresh;
- lastError?: OperationErrorDetails;
- refreshGroupId: string;
- finishedPerCoin: boolean[];
- retryInfo: RetryInfo;
-}
-
-/**
- * Status of downloading signed contract terms from a merchant.
- */
-export interface PendingProposalDownloadOperation {
- type: PendingOperationType.ProposalDownload;
- merchantBaseUrl: string;
- proposalTimestamp: Timestamp;
- proposalId: string;
- orderId: string;
- lastError?: OperationErrorDetails;
- retryInfo: RetryInfo;
-}
-
-/**
- * User must choose whether to accept or reject the merchant's
- * proposed contract terms.
- */
-export interface PendingProposalChoiceOperation {
- type: PendingOperationType.ProposalChoice;
- merchantBaseUrl: string;
- proposalTimestamp: Timestamp;
- proposalId: string;
-}
-
-/**
- * The wallet is picking up a tip that the user has accepted.
- */
-export interface PendingTipPickupOperation {
- type: PendingOperationType.TipPickup;
- tipId: string;
- merchantBaseUrl: string;
- merchantTipId: string;
-}
-
-/**
- * The wallet has been offered a tip, and the user now needs to
- * decide whether to accept or reject the tip.
- */
-export interface PendingTipChoiceOperation {
- type: PendingOperationType.TipChoice;
- tipId: string;
- merchantBaseUrl: string;
- merchantTipId: string;
-}
-
-/**
- * The wallet is signing coins and then sending them to
- * the merchant.
- */
-export interface PendingPayOperation {
- type: PendingOperationType.Pay;
- proposalId: string;
- isReplay: boolean;
- retryInfo: RetryInfo;
- lastError: OperationErrorDetails | undefined;
-}
-
-/**
- * The wallet is querying the merchant about whether any refund
- * permissions are available for a purchase.
- */
-export interface PendingRefundQueryOperation {
- type: PendingOperationType.RefundQuery;
- proposalId: string;
- retryInfo: RetryInfo;
- lastError: OperationErrorDetails | undefined;
-}
-
-export interface PendingRecoupOperation {
- type: PendingOperationType.Recoup;
- recoupGroupId: string;
- retryInfo: RetryInfo;
- lastError: OperationErrorDetails | undefined;
-}
-
-/**
- * Status of an ongoing withdrawal operation.
- */
-export interface PendingWithdrawOperation {
- type: PendingOperationType.Withdraw;
- source: WithdrawalSource;
- lastError: OperationErrorDetails | undefined;
- withdrawalGroupId: string;
- numCoinsWithdrawn: number;
- numCoinsTotal: number;
-}
-
-/**
- * Fields that are present in every pending operation.
- */
-export interface PendingOperationInfoCommon {
- /**
- * Type of the pending operation.
- */
- type: PendingOperationType;
-
- /**
- * Set to true if the operation indicates that something is really in progress,
- * as opposed to some regular scheduled operation or a permanent failure.
- */
- givesLifeness: boolean;
-}
-
-/**
- * Response returned from the pending operations API.
- */
-export interface PendingOperationsResponse {
- /**
- * List of pending operations.
- */
- pendingOperations: PendingOperationInfo[];
-
- /**
- * Current wallet balance, including pending balances.
- */
- walletBalance: BalancesResponse;
-
- /**
- * When is the next pending operation due to be re-tried?
- */
- nextRetryDelay: Duration;
-
- /**
- * Does this response only include pending operations that
- * are due to be executed right now?
- */
- onlyDue: boolean;
-}
diff --git a/src/types/schemacore.ts b/src/types/schemacore.ts
deleted file mode 100644
index 820f68d18..000000000
--- a/src/types/schemacore.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- 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/>
- */
-
-/**
- * Core of the wallet's schema, used for painless export, import
- * and schema migration.
- *
- * If this schema is extended, it must be extended in a completely
- * backwards-compatible way.
- */
-
-interface CoreCoin {
- exchangeBaseUrl: string;
- coinPub: string;
- coinPriv: string;
- amountRemaining: string;
-}
-
-interface CorePurchase {
- noncePub: string;
- noncePriv: string;
- paySig: string;
- contractTerms: any;
-}
-
-interface CoreReserve {
- reservePub: string;
- reservePriv: string;
- exchangeBaseUrl: string;
-}
-
-interface SchemaCore {
- coins: CoreCoin[];
- purchases: CorePurchase[];
-
- /**
- * Schema version (of full schema) of wallet that exported the core schema.
- */
- versionExporter: number;
-
- /**
- * Schema version of the database that has been exported to the core schema
- */
- versionSourceDatabase: number;
-}
diff --git a/src/types/talerTypes.ts b/src/types/talerTypes.ts
deleted file mode 100644
index 95c1a711c..000000000
--- a/src/types/talerTypes.ts
+++ /dev/null
@@ -1,1271 +0,0 @@
-/*
- 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/>
- */
-
-/**
- * Type and schema definitions and helpers for the core GNU Taler protocol.
- *
- * All types here should be "@Checkable".
- *
- * Even though the rest of the wallet uses camelCase for fields, use snake_case
- * here, since that's the convention for the Taler JSON+HTTP API.
- */
-
-/**
- * Imports.
- */
-
-import {
- makeCodecForObject,
- codecForString,
- makeCodecForList,
- makeCodecOptional,
- codecForAny,
- codecForNumber,
- codecForBoolean,
- makeCodecForMap,
- Codec,
- makeCodecForConstNumber,
- makeCodecForUnion,
- makeCodecForConstString,
-} from "../util/codec";
-import {
- Timestamp,
- codecForTimestamp,
- Duration,
- codecForDuration,
-} from "../util/time";
-import { ExchangeListItem } from "./walletTypes";
-
-/**
- * Denomination as found in the /keys response from the exchange.
- */
-export class Denomination {
- /**
- * Value of one coin of the denomination.
- */
- value: string;
-
- /**
- * Public signing key of the denomination.
- */
- denom_pub: string;
-
- /**
- * Fee for withdrawing.
- */
- fee_withdraw: string;
-
- /**
- * Fee for depositing.
- */
- fee_deposit: string;
-
- /**
- * Fee for refreshing.
- */
- fee_refresh: string;
-
- /**
- * Fee for refunding.
- */
- fee_refund: string;
-
- /**
- * Start date from which withdraw is allowed.
- */
- stamp_start: Timestamp;
-
- /**
- * End date for withdrawing.
- */
- stamp_expire_withdraw: Timestamp;
-
- /**
- * Expiration date after which the exchange can forget about
- * the currency.
- */
- stamp_expire_legal: Timestamp;
-
- /**
- * Date after which the coins of this denomination can't be
- * deposited anymore.
- */
- stamp_expire_deposit: Timestamp;
-
- /**
- * Signature over the denomination information by the exchange's master
- * signing key.
- */
- master_sig: string;
-}
-
-/**
- * Signature by the auditor that a particular denomination key is audited.
- */
-export class AuditorDenomSig {
- /**
- * Denomination public key's hash.
- */
- denom_pub_h: string;
-
- /**
- * The signature.
- */
- auditor_sig: string;
-}
-
-/**
- * Auditor information as given by the exchange in /keys.
- */
-export class Auditor {
- /**
- * Auditor's public key.
- */
- auditor_pub: string;
-
- /**
- * Base URL of the auditor.
- */
- auditor_url: string;
-
- /**
- * List of signatures for denominations by the auditor.
- */
- denomination_keys: AuditorDenomSig[];
-}
-
-/**
- * Request that we send to the exchange to get a payback.
- */
-export interface RecoupRequest {
- /**
- * Hashed enomination public key of the coin we want to get
- * paid back.
- */
- denom_pub_hash: string;
-
- /**
- * Signature over the coin public key by the denomination.
- */
- denom_sig: string;
-
- /**
- * Coin public key of the coin we want to refund.
- */
- coin_pub: string;
-
- /**
- * Blinding key that was used during withdraw,
- * used to prove that we were actually withdrawing the coin.
- */
- coin_blind_key_secret: string;
-
- /**
- * Signature made by the coin, authorizing the payback.
- */
- coin_sig: string;
-
- /**
- * Was the coin refreshed (and thus the recoup should go to the old coin)?
- */
- refreshed: boolean;
-}
-
-/**
- * Response that we get from the exchange for a payback request.
- */
-export class RecoupConfirmation {
- /**
- * Public key of the reserve that will receive the payback.
- */
- reserve_pub?: string;
-
- /**
- * Public key of the old coin that will receive the recoup,
- * provided if refreshed was true.
- */
- old_coin_pub?: string;
-}
-
-/**
- * Deposit permission for a single coin.
- */
-export interface CoinDepositPermission {
- /**
- * Signature by the coin.
- */
- coin_sig: string;
- /**
- * Public key of the coin being spend.
- */
- coin_pub: string;
- /**
- * Signature made by the denomination public key.
- */
- ub_sig: string;
- /**
- * The denomination public key associated with this coin.
- */
- h_denom: string;
- /**
- * The amount that is subtracted from this coin with this payment.
- */
- contribution: string;
-
- /**
- * URL of the exchange this coin was withdrawn from.
- */
- exchange_url: string;
-}
-
-/**
- * Information about an exchange as stored inside a
- * merchant's contract terms.
- */
-export class ExchangeHandle {
- /**
- * Master public signing key of the exchange.
- */
- master_pub: string;
-
- /**
- * Base URL of the exchange.
- */
- url: string;
-}
-
-export class AuditorHandle {
- /**
- * Official name of the auditor.
- */
- name: string;
-
- /**
- * Master public signing key of the auditor.
- */
- master_pub: string;
-
- /**
- * Base URL of the auditor.
- */
- url: string;
-}
-
-export interface MerchantInfo {
- name: string;
- jurisdiction: string | undefined;
- address: string | undefined;
-}
-
-export interface Tax {
- // the name of the tax
- name: string;
-
- // amount paid in tax
- tax: AmountString;
-}
-
-export interface Product {
- // merchant-internal identifier for the product.
- product_id?: string;
-
- // Human-readable product description.
- description: string;
-
- // Map from IETF BCP 47 language tags to localized descriptions
- description_i18n?: { [lang_tag: string]: string };
-
- // The number of units of the product to deliver to the customer.
- quantity?: number;
-
- // The unit in which the product is measured (liters, kilograms, packages, etc.)
- unit?: string;
-
- // The price of the product; this is the total price for quantity times unit of this product.
- price?: AmountString;
-
- // An optional base64-encoded product image
- image?: string;
-
- // a list of taxes paid by the merchant for this product. Can be empty.
- taxes?: Tax[];
-
- // time indicating when this product should be delivered
- delivery_date?: Timestamp;
-
- // where to deliver this product. This may be an URL for online delivery
- // (i.e. 'http://example.com/download' or 'mailto:customer@example.com'),
- // or a location label defined inside the proposition's 'locations'.
- // The presence of a colon (':') indicates the use of an URL.
- delivery_location?: string;
-}
-
-/**
- * Contract terms from a merchant.
- */
-export class ContractTerms {
- /**
- * Hash of the merchant's wire details.
- */
- h_wire: string;
-
- /**
- * Hash of the merchant's wire details.
- */
- auto_refund?: Duration;
-
- /**
- * Wire method the merchant wants to use.
- */
- wire_method: string;
-
- /**
- * Human-readable short summary of the contract.
- */
- summary: string;
-
- summary_i18n?: { [lang_tag: string]: string };
-
- /**
- * Nonce used to ensure freshness.
- */
- nonce: string;
-
- /**
- * Total amount payable.
- */
- amount: string;
-
- /**
- * Auditors accepted by the merchant.
- */
- auditors: AuditorHandle[];
-
- /**
- * Deadline to pay for the contract.
- */
- pay_deadline: Timestamp;
-
- /**
- * Delivery locations.
- */
- locations: any;
-
- /**
- * Maximum deposit fee covered by the merchant.
- */
- max_fee: string;
-
- /**
- * Information about the merchant.
- */
- merchant: MerchantInfo;
-
- /**
- * Public key of the merchant.
- */
- merchant_pub: string;
-
- /**
- * List of accepted exchanges.
- */
- exchanges: ExchangeHandle[];
-
- /**
- * Products that are sold in this contract.
- */
- products?: Product[];
-
- /**
- * Deadline for refunds.
- */
- refund_deadline: Timestamp;
-
- /**
- * Deadline for the wire transfer.
- */
- wire_transfer_deadline: Timestamp;
-
- /**
- * Time when the contract was generated by the merchant.
- */
- timestamp: Timestamp;
-
- /**
- * Order id to uniquely identify the purchase within
- * one merchant instance.
- */
- order_id: string;
-
- /**
- * Base URL of the merchant's backend.
- */
- merchant_base_url: string;
-
- /**
- * Fulfillment URL to view the product or
- * delivery status.
- */
- fulfillment_url: string;
-
- /**
- * Share of the wire fee that must be settled with one payment.
- */
- wire_fee_amortization?: number;
-
- /**
- * Maximum wire fee that the merchant agrees to pay for.
- */
- max_wire_fee?: string;
-
- /**
- * Extra data, interpreted by the mechant only.
- */
- extra: any;
-}
-
-/**
- * Refund permission in the format that the merchant gives it to us.
- */
-export class MerchantAbortPayRefundDetails {
- /**
- * Amount to be refunded.
- */
- refund_amount: string;
-
- /**
- * Fee for the refund.
- */
- refund_fee: string;
-
- /**
- * Public key of the coin being refunded.
- */
- coin_pub: string;
-
- /**
- * Refund transaction ID between merchant and exchange.
- */
- rtransaction_id: number;
-
- /**
- * Exchange's key used for the signature.
- */
- exchange_pub?: string;
-
- /**
- * Exchange's signature to confirm the refund.
- */
- exchange_sig?: string;
-
- /**
- * Error replay from the exchange (if any).
- */
- exchange_reply?: any;
-
- /**
- * Error code from the exchange (if any).
- */
- exchange_code?: number;
-
- /**
- * HTTP status code of the exchange's response
- * to the merchant's refund request.
- */
- exchange_http_status: number;
-}
-
-/**
- * Response for a refund pickup or a /pay in abort mode.
- */
-export class MerchantRefundResponse {
- /**
- * Public key of the merchant
- */
- merchant_pub: string;
-
- /**
- * Contract terms hash of the contract that
- * is being refunded.
- */
- h_contract_terms: string;
-
- /**
- * The signed refund permissions, to be sent to the exchange.
- */
- refunds: MerchantAbortPayRefundDetails[];
-}
-
-/**
- * Planchet detail sent to the merchant.
- */
-export interface TipPlanchetDetail {
- /**
- * Hashed denomination public key.
- */
- denom_pub_hash: string;
-
- /**
- * Coin's blinded public key.
- */
- coin_ev: string;
-}
-
-/**
- * Request sent to the merchant to pick up a tip.
- */
-export interface TipPickupRequest {
- /**
- * Identifier of the tip.
- */
- tip_id: string;
-
- /**
- * List of planchets the wallet wants to use for the tip.
- */
- planchets: TipPlanchetDetail[];
-}
-
-/**
- * Reserve signature, defined as separate class to facilitate
- * schema validation with "@Checkable".
- */
-export class ReserveSigSingleton {
- /**
- * Reserve signature.
- */
- reserve_sig: string;
-}
-
-/**
- * Response of the merchant
- * to the TipPickupRequest.
- */
-export class TipResponse {
- /**
- * Public key of the reserve
- */
- reserve_pub: string;
-
- /**
- * The order of the signatures matches the planchets list.
- */
- reserve_sigs: ReserveSigSingleton[];
-}
-
-/**
- * Element of the payback list that the
- * exchange gives us in /keys.
- */
-export class Recoup {
- /**
- * The hash of the denomination public key for which the payback is offered.
- */
- h_denom_pub: string;
-}
-
-/**
- * Structure of one exchange signing key in the /keys response.
- */
-export class ExchangeSignKeyJson {
- stamp_start: Timestamp;
- stamp_expire: Timestamp;
- stamp_end: Timestamp;
- key: EddsaPublicKeyString;
- master_sig: EddsaSignatureString;
-}
-
-/**
- * Structure that the exchange gives us in /keys.
- */
-export class ExchangeKeysJson {
- /**
- * List of offered denominations.
- */
- denoms: Denomination[];
-
- /**
- * The exchange's master public key.
- */
- master_public_key: string;
-
- /**
- * The list of auditors (partially) auditing the exchange.
- */
- auditors: Auditor[];
-
- /**
- * Timestamp when this response was issued.
- */
- list_issue_date: Timestamp;
-
- /**
- * List of revoked denominations.
- */
- recoup?: Recoup[];
-
- /**
- * Short-lived signing keys used to sign online
- * responses.
- */
- signkeys: ExchangeSignKeyJson[];
-
- /**
- * Protocol version.
- */
- version: string;
-}
-
-/**
- * Wire fees as anounced by the exchange.
- */
-export class WireFeesJson {
- /**
- * Cost of a wire transfer.
- */
- wire_fee: string;
-
- /**
- * Cost of clising a reserve.
- */
- closing_fee: string;
-
- /**
- * Signature made with the exchange's master key.
- */
- sig: string;
-
- /**
- * Date from which the fee applies.
- */
- start_date: Timestamp;
-
- /**
- * Data after which the fee doesn't apply anymore.
- */
- end_date: Timestamp;
-}
-
-export class AccountInfo {
- payto_uri: string;
- master_sig: string;
-}
-
-export class ExchangeWireJson {
- accounts: AccountInfo[];
- fees: { [methodName: string]: WireFeesJson[] };
-}
-
-/**
- * Proposal returned from the contract URL.
- */
-export class Proposal {
- /**
- * Contract terms for the propoal.
- * Raw, un-decoded JSON object.
- */
- contract_terms: any;
-
- /**
- * Signature over contract, made by the merchant. The public key used for signing
- * must be contract_terms.merchant_pub.
- */
- sig: string;
-}
-
-/**
- * Response from the internal merchant API.
- */
-export class CheckPaymentResponse {
- order_status: string;
- refunded: boolean | undefined;
- refunded_amount: string | undefined;
- contract_terms: any | undefined;
- taler_pay_uri: string | undefined;
- contract_url: string | undefined;
-}
-
-/**
- * Response from the bank.
- */
-export class WithdrawOperationStatusResponse {
- selection_done: boolean;
-
- transfer_done: boolean;
-
- amount: string;
-
- sender_wire?: string;
-
- suggested_exchange?: string;
-
- confirm_transfer_url?: string;
-
- wire_types: string[];
-}
-
-/**
- * Response from the merchant.
- */
-export class TipPickupGetResponse {
- extra: any;
-
- amount: string;
-
- amount_left: string;
-
- exchange_url: string;
-
- stamp_expire: Timestamp;
-
- stamp_created: Timestamp;
-}
-
-export class WithdrawResponse {
- ev_sig: string;
-}
-
-/**
- * Easy to process format for the public data of coins
- * managed by the wallet.
- */
-export interface CoinDumpJson {
- coins: Array<{
- /**
- * The coin's denomination's public key.
- */
- denom_pub: string;
- /**
- * Hash of denom_pub.
- */
- denom_pub_hash: string;
- /**
- * Value of the denomination (without any fees).
- */
- denom_value: string;
- /**
- * Public key of the coin.
- */
- coin_pub: string;
- /**
- * Base URL of the exchange for the coin.
- */
- exchange_base_url: string;
- /**
- * Remaining value on the coin, to the knowledge of
- * the wallet.
- */
- remaining_value: string;
- /**
- * Public key of the parent coin.
- * Only present if this coin was obtained via refreshing.
- */
- refresh_parent_coin_pub: string | undefined;
- /**
- * Public key of the reserve for this coin.
- * Only present if this coin was obtained via refreshing.
- */
- withdrawal_reserve_pub: string | undefined;
- /**
- * Is the coin suspended?
- * Suspended coins are not considered for payments.
- */
- coin_suspended: boolean;
- }>;
-}
-
-export interface MerchantPayResponse {
- sig: string;
-}
-
-export interface ExchangeMeltResponse {
- /**
- * Which of the kappa indices does the client not have to reveal.
- */
- noreveal_index: number;
-
- /**
- * Signature of TALER_RefreshMeltConfirmationPS whereby the exchange
- * affirms the successful melt and confirming the noreveal_index
- */
- exchange_sig: EddsaSignatureString;
-
- /*
- * public EdDSA key of the exchange that was used to generate the signature.
- * Should match one of the exchange's signing keys from /keys. Again given
- * explicitly as the client might otherwise be confused by clock skew as to
- * which signing key was used.
- */
- exchange_pub: EddsaPublicKeyString;
-
- /*
- * Base URL to use for operations on the refresh context
- * (so the reveal operation). If not given,
- * the base URL is the same as the one used for this request.
- * Can be used if the base URL for /refreshes/ differs from that
- * for /coins/, i.e. for load balancing. Clients SHOULD
- * respect the refresh_base_url if provided. Any HTTP server
- * belonging to an exchange MUST generate a 307 or 308 redirection
- * to the correct base URL should a client uses the wrong base
- * URL, or if the base URL has changed since the melt.
- *
- * When melting the same coin twice (technically allowed
- * as the response might have been lost on the network),
- * the exchange may return different values for the refresh_base_url.
- */
- refresh_base_url?: string;
-}
-
-export interface ExchangeRevealItem {
- ev_sig: string;
-}
-
-export interface ExchangeRevealResponse {
- // List of the exchange's blinded RSA signatures on the new coins.
- ev_sigs: ExchangeRevealItem[];
-}
-
-interface MerchantOrderStatusPaid {
-
- /**
- * Was the payment refunded (even partially, via refund or abort)?
- */
- refunded: boolean;
-
- /**
- * Amount that was refunded in total.
- */
- refund_amount: AmountString;
-
- /**
- * Successful refunds for this payment, empty array for none.
- */
- refunds: MerchantCoinRefundStatus[];
-
- /**
- * Public key of the merchant.
- */
- merchant_pub: EddsaPublicKeyString;
-}
-
-export type MerchantCoinRefundStatus =
- | MerchantCoinRefundSuccessStatus
- | MerchantCoinRefundFailureStatus;
-
-export interface MerchantCoinRefundSuccessStatus {
- type: "success";
-
- // HTTP status of the exchange request, 200 (integer) required for refund confirmations.
- exchange_status: 200;
-
- // the EdDSA :ref:signature (binary-only) with purpose
- // TALER_SIGNATURE_EXCHANGE_CONFIRM_REFUND using a current signing key of the
- // exchange affirming the successful refund
- exchange_sig: EddsaSignatureString;
-
- // public EdDSA key of the exchange that was used to generate the signature.
- // Should match one of the exchange's signing keys from /keys. It is given
- // explicitly as the client might otherwise be confused by clock skew as to
- // which signing key was used.
- exchange_pub: EddsaPublicKeyString;
-
- // Refund transaction ID.
- rtransaction_id: number;
-
- // public key of a coin that was refunded
- coin_pub: EddsaPublicKeyString;
-
- // Amount that was refunded, including refund fee charged by the exchange
- // to the customer.
- refund_amount: AmountString;
-
- execution_time: Timestamp;
-}
-
-export interface MerchantCoinRefundFailureStatus {
- type: "failure";
-
- // HTTP status of the exchange request, must NOT be 200.
- exchange_status: number;
-
- // Taler error code from the exchange reply, if available.
- exchange_code?: number;
-
- // If available, HTTP reply from the exchange.
- exchange_reply?: any;
-
- // Refund transaction ID.
- rtransaction_id: number;
-
- // public key of a coin that was refunded
- coin_pub: EddsaPublicKeyString;
-
- // Amount that was refunded, including refund fee charged by the exchange
- // to the customer.
- refund_amount: AmountString;
-
- execution_time: Timestamp;
-}
-
-export interface MerchantOrderStatusUnpaid {
- /**
- * URI that the wallet must process to complete the payment.
- */
- taler_pay_uri: string;
-
- /**
- * Alternative order ID which was paid for already in the same session.
- *
- * Only given if the same product was purchased before in the same session.
- */
- already_paid_order_id?: string;
-}
-
-export interface WithdrawUriInfoResponse {
- amount: AmountString;
- defaultExchangeBaseUrl?: string;
- possibleExchanges: ExchangeListItem[];
-}
-
-/**
- * Response body for the following endpoint:
- *
- * POST {talerBankIntegrationApi}/withdrawal-operation/{wopid}
- */
-export interface BankWithdrawalOperationPostResponse {
- transfer_done: boolean;
-}
-
-export const codecForBankWithdrawalOperationPostResponse = (): Codec<BankWithdrawalOperationPostResponse> =>
- makeCodecForObject<BankWithdrawalOperationPostResponse>()
- .property("transfer_done", codecForBoolean)
- .build("BankWithdrawalOperationPostResponse");
-
-export type AmountString = string;
-export type Base32String = string;
-export type EddsaSignatureString = string;
-export type EddsaPublicKeyString = string;
-export type CoinPublicKeyString = string;
-
-export const codecForDenomination = (): Codec<Denomination> =>
- makeCodecForObject<Denomination>()
- .property("value", codecForString)
- .property("denom_pub", codecForString)
- .property("fee_withdraw", codecForString)
- .property("fee_deposit", codecForString)
- .property("fee_refresh", codecForString)
- .property("fee_refund", codecForString)
- .property("stamp_start", codecForTimestamp)
- .property("stamp_expire_withdraw", codecForTimestamp)
- .property("stamp_expire_legal", codecForTimestamp)
- .property("stamp_expire_deposit", codecForTimestamp)
- .property("master_sig", codecForString)
- .build("Denomination");
-
-export const codecForAuditorDenomSig = (): Codec<AuditorDenomSig> =>
- makeCodecForObject<AuditorDenomSig>()
- .property("denom_pub_h", codecForString)
- .property("auditor_sig", codecForString)
- .build("AuditorDenomSig");
-
-export const codecForAuditor = (): Codec<Auditor> =>
- makeCodecForObject<Auditor>()
- .property("auditor_pub", codecForString)
- .property("auditor_url", codecForString)
- .property("denomination_keys", makeCodecForList(codecForAuditorDenomSig()))
- .build("Auditor");
-
-export const codecForExchangeHandle = (): Codec<ExchangeHandle> =>
- makeCodecForObject<ExchangeHandle>()
- .property("master_pub", codecForString)
- .property("url", codecForString)
- .build("ExchangeHandle");
-
-export const codecForAuditorHandle = (): Codec<AuditorHandle> =>
- makeCodecForObject<AuditorHandle>()
- .property("name", codecForString)
- .property("master_pub", codecForString)
- .property("url", codecForString)
- .build("AuditorHandle");
-
-export const codecForMerchantInfo = (): Codec<MerchantInfo> =>
- makeCodecForObject<MerchantInfo>()
- .property("name", codecForString)
- .property("address", makeCodecOptional(codecForString))
- .property("jurisdiction", makeCodecOptional(codecForString))
- .build("MerchantInfo");
-
-export const codecForTax = (): Codec<Tax> =>
- makeCodecForObject<Tax>()
- .property("name", codecForString)
- .property("tax", codecForString)
- .build("Tax");
-
-export const codecForI18n = (): Codec<{ [lang_tag: string]: string }> =>
- makeCodecForMap(codecForString);
-
-export const codecForProduct = (): Codec<Product> =>
- makeCodecForObject<Product>()
- .property("product_id", makeCodecOptional(codecForString))
- .property("description", codecForString)
- .property("description_i18n", makeCodecOptional(codecForI18n()))
- .property("quantity", makeCodecOptional(codecForNumber))
- .property("unit", makeCodecOptional(codecForString))
- .property("price", makeCodecOptional(codecForString))
- .property("delivery_date", makeCodecOptional(codecForTimestamp))
- .property("delivery_location", makeCodecOptional(codecForString))
- .build("Tax");
-
-export const codecForContractTerms = (): Codec<ContractTerms> =>
- makeCodecForObject<ContractTerms>()
- .property("order_id", codecForString)
- .property("fulfillment_url", codecForString)
- .property("merchant_base_url", codecForString)
- .property("h_wire", codecForString)
- .property("auto_refund", makeCodecOptional(codecForDuration))
- .property("wire_method", codecForString)
- .property("summary", codecForString)
- .property("summary_i18n", makeCodecOptional(codecForI18n()))
- .property("nonce", codecForString)
- .property("amount", codecForString)
- .property("auditors", makeCodecForList(codecForAuditorHandle()))
- .property("pay_deadline", codecForTimestamp)
- .property("refund_deadline", codecForTimestamp)
- .property("wire_transfer_deadline", codecForTimestamp)
- .property("timestamp", codecForTimestamp)
- .property("locations", codecForAny)
- .property("max_fee", codecForString)
- .property("max_wire_fee", makeCodecOptional(codecForString))
- .property("merchant", codecForMerchantInfo())
- .property("merchant_pub", codecForString)
- .property("exchanges", makeCodecForList(codecForExchangeHandle()))
- .property(
- "products",
- makeCodecOptional(makeCodecForList(codecForProduct())),
- )
- .property("extra", codecForAny)
- .build("ContractTerms");
-
-export const codecForMerchantRefundPermission = (): Codec<
- MerchantAbortPayRefundDetails
-> =>
- makeCodecForObject<MerchantAbortPayRefundDetails>()
- .property("refund_amount", codecForString)
- .property("refund_fee", codecForString)
- .property("coin_pub", codecForString)
- .property("rtransaction_id", codecForNumber)
- .property("exchange_http_status", codecForNumber)
- .property("exchange_code", makeCodecOptional(codecForNumber))
- .property("exchange_reply", makeCodecOptional(codecForAny))
- .property("exchange_sig", makeCodecOptional(codecForString))
- .property("exchange_pub", makeCodecOptional(codecForString))
- .build("MerchantRefundPermission");
-
-export const codecForMerchantRefundResponse = (): Codec<
- MerchantRefundResponse
-> =>
- makeCodecForObject<MerchantRefundResponse>()
- .property("merchant_pub", codecForString)
- .property("h_contract_terms", codecForString)
- .property("refunds", makeCodecForList(codecForMerchantRefundPermission()))
- .build("MerchantRefundResponse");
-
-export const codecForReserveSigSingleton = (): Codec<ReserveSigSingleton> =>
- makeCodecForObject<ReserveSigSingleton>()
- .property("reserve_sig", codecForString)
- .build("ReserveSigSingleton");
-
-export const codecForTipResponse = (): Codec<TipResponse> =>
- makeCodecForObject<TipResponse>()
- .property("reserve_pub", codecForString)
- .property("reserve_sigs", makeCodecForList(codecForReserveSigSingleton()))
- .build("TipResponse");
-
-export const codecForRecoup = (): Codec<Recoup> =>
- makeCodecForObject<Recoup>()
- .property("h_denom_pub", codecForString)
- .build("Recoup");
-
-export const codecForExchangeSigningKey = (): Codec<ExchangeSignKeyJson> =>
- makeCodecForObject<ExchangeSignKeyJson>()
- .property("key", codecForString)
- .property("master_sig", codecForString)
- .property("stamp_end", codecForTimestamp)
- .property("stamp_start", codecForTimestamp)
- .property("stamp_expire", codecForTimestamp)
- .build("ExchangeSignKeyJson");
-
-export const codecForExchangeKeysJson = (): Codec<ExchangeKeysJson> =>
- makeCodecForObject<ExchangeKeysJson>()
- .property("denoms", makeCodecForList(codecForDenomination()))
- .property("master_public_key", codecForString)
- .property("auditors", makeCodecForList(codecForAuditor()))
- .property("list_issue_date", codecForTimestamp)
- .property("recoup", makeCodecOptional(makeCodecForList(codecForRecoup())))
- .property("signkeys", makeCodecForList(codecForExchangeSigningKey()))
- .property("version", codecForString)
- .build("KeysJson");
-
-export const codecForWireFeesJson = (): Codec<WireFeesJson> =>
- makeCodecForObject<WireFeesJson>()
- .property("wire_fee", codecForString)
- .property("closing_fee", codecForString)
- .property("sig", codecForString)
- .property("start_date", codecForTimestamp)
- .property("end_date", codecForTimestamp)
- .build("WireFeesJson");
-
-export const codecForAccountInfo = (): Codec<AccountInfo> =>
- makeCodecForObject<AccountInfo>()
- .property("payto_uri", codecForString)
- .property("master_sig", codecForString)
- .build("AccountInfo");
-
-export const codecForExchangeWireJson = (): Codec<ExchangeWireJson> =>
- makeCodecForObject<ExchangeWireJson>()
- .property("accounts", makeCodecForList(codecForAccountInfo()))
- .property("fees", makeCodecForMap(makeCodecForList(codecForWireFeesJson())))
- .build("ExchangeWireJson");
-
-export const codecForProposal = (): Codec<Proposal> =>
- makeCodecForObject<Proposal>()
- .property("contract_terms", codecForAny)
- .property("sig", codecForString)
- .build("Proposal");
-
-export const codecForCheckPaymentResponse = (): Codec<CheckPaymentResponse> =>
- makeCodecForObject<CheckPaymentResponse>()
- .property("order_status", codecForString)
- .property("refunded", makeCodecOptional(codecForBoolean))
- .property("refunded_amount", makeCodecOptional(codecForString))
- .property("contract_terms", makeCodecOptional(codecForAny))
- .property("taler_pay_uri", makeCodecOptional(codecForString))
- .property("contract_url", makeCodecOptional(codecForString))
- .build("CheckPaymentResponse");
-
-export const codecForWithdrawOperationStatusResponse = (): Codec<
- WithdrawOperationStatusResponse
-> =>
- makeCodecForObject<WithdrawOperationStatusResponse>()
- .property("selection_done", codecForBoolean)
- .property("transfer_done", codecForBoolean)
- .property("amount", codecForString)
- .property("sender_wire", makeCodecOptional(codecForString))
- .property("suggested_exchange", makeCodecOptional(codecForString))
- .property("confirm_transfer_url", makeCodecOptional(codecForString))
- .property("wire_types", makeCodecForList(codecForString))
- .build("WithdrawOperationStatusResponse");
-
-export const codecForTipPickupGetResponse = (): Codec<TipPickupGetResponse> =>
- makeCodecForObject<TipPickupGetResponse>()
- .property("extra", codecForAny)
- .property("amount", codecForString)
- .property("amount_left", codecForString)
- .property("exchange_url", codecForString)
- .property("stamp_expire", codecForTimestamp)
- .property("stamp_created", codecForTimestamp)
- .build("TipPickupGetResponse");
-
-export const codecForRecoupConfirmation = (): Codec<RecoupConfirmation> =>
- makeCodecForObject<RecoupConfirmation>()
- .property("reserve_pub", makeCodecOptional(codecForString))
- .property("old_coin_pub", makeCodecOptional(codecForString))
- .build("RecoupConfirmation");
-
-export const codecForWithdrawResponse = (): Codec<WithdrawResponse> =>
- makeCodecForObject<WithdrawResponse>()
- .property("ev_sig", codecForString)
- .build("WithdrawResponse");
-
-export const codecForMerchantPayResponse = (): Codec<MerchantPayResponse> =>
- makeCodecForObject<MerchantPayResponse>()
- .property("sig", codecForString)
- .build("MerchantPayResponse");
-
-export const codecForExchangeMeltResponse = (): Codec<ExchangeMeltResponse> =>
- makeCodecForObject<ExchangeMeltResponse>()
- .property("exchange_pub", codecForString)
- .property("exchange_sig", codecForString)
- .property("noreveal_index", codecForNumber)
- .property("refresh_base_url", makeCodecOptional(codecForString))
- .build("ExchangeMeltResponse");
-
-export const codecForExchangeRevealItem = (): Codec<ExchangeRevealItem> =>
- makeCodecForObject<ExchangeRevealItem>()
- .property("ev_sig", codecForString)
- .build("ExchangeRevealItem");
-
-export const codecForExchangeRevealResponse = (): Codec<
- ExchangeRevealResponse
-> =>
- makeCodecForObject<ExchangeRevealResponse>()
- .property("ev_sigs", makeCodecForList(codecForExchangeRevealItem()))
- .build("ExchangeRevealResponse");
-
-export const codecForMerchantCoinRefundSuccessStatus = (): Codec<
- MerchantCoinRefundSuccessStatus
-> =>
- makeCodecForObject<MerchantCoinRefundSuccessStatus>()
- .property("type", makeCodecForConstString("success"))
- .property("coin_pub", codecForString)
- .property("exchange_status", makeCodecForConstNumber(200))
- .property("exchange_sig", codecForString)
- .property("rtransaction_id", codecForNumber)
- .property("refund_amount", codecForString)
- .property("exchange_pub", codecForString)
- .property("execution_time", codecForTimestamp)
- .build("MerchantCoinRefundSuccessStatus");
-
-export const codecForMerchantCoinRefundFailureStatus = (): Codec<
- MerchantCoinRefundFailureStatus
-> =>
- makeCodecForObject<MerchantCoinRefundFailureStatus>()
- .property("type", makeCodecForConstString("failure"))
- .property("coin_pub", codecForString)
- .property("exchange_status", makeCodecForConstNumber(200))
- .property("rtransaction_id", codecForNumber)
- .property("refund_amount", codecForString)
- .property("exchange_code", makeCodecOptional(codecForNumber))
- .property("exchange_reply", makeCodecOptional(codecForAny))
- .property("execution_time", codecForTimestamp)
- .build("MerchantCoinRefundSuccessStatus");
-
-export const codecForMerchantCoinRefundStatus = (): Codec<
- MerchantCoinRefundStatus
-> =>
- makeCodecForUnion<MerchantCoinRefundStatus>()
- .discriminateOn("type")
- .alternative("success", codecForMerchantCoinRefundSuccessStatus())
- .alternative("failure", codecForMerchantCoinRefundFailureStatus())
- .build("MerchantCoinRefundStatus");
-
-export const codecForMerchantOrderStatusPaid = (): Codec<
- MerchantOrderStatusPaid
-> =>
- makeCodecForObject<MerchantOrderStatusPaid>()
- .property("merchant_pub", codecForString)
- .property("refund_amount", codecForString)
- .property("refunded", codecForBoolean)
- .property("refunds", makeCodecForList(codecForMerchantCoinRefundStatus()))
- .build("MerchantOrderStatusPaid");
-
-export const codecForMerchantOrderStatusUnpaid = (): Codec<
- MerchantOrderStatusUnpaid
-> =>
- makeCodecForObject<MerchantOrderStatusUnpaid>()
- .property("taler_pay_uri", codecForString)
- .property("already_paid_order_id", makeCodecOptional(codecForString))
- .build("MerchantOrderStatusUnpaid");
diff --git a/src/types/transactions.ts b/src/types/transactions.ts
deleted file mode 100644
index a6ea37e7a..000000000
--- a/src/types/transactions.ts
+++ /dev/null
@@ -1,310 +0,0 @@
-/*
- 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/>
- */
-
-/**
- * Type and schema definitions for the wallet's transaction list.
- *
- * @author Florian Dold
- * @author Torsten Grote
- */
-
-/**
- * Imports.
- */
-import { Timestamp } from "../util/time";
-import { AmountString, Product } from "./talerTypes";
-import { Codec, makeCodecForObject, makeCodecOptional, codecForString } from "../util/codec";
-
-export interface TransactionsRequest {
- /**
- * return only transactions in the given currency
- */
- currency?: string;
-
- /**
- * if present, results will be limited to transactions related to the given search string
- */
- search?: string;
-}
-
-export interface TransactionsResponse {
- // a list of past and pending transactions sorted by pending, timestamp and transactionId.
- // In case two events are both pending and have the same timestamp,
- // they are sorted by the transactionId
- // (lexically ascending and locale-independent comparison).
- transactions: Transaction[];
-}
-
-interface TransactionError {
- /**
- * TALER_EC_* unique error code.
- * The action(s) offered and message displayed on the transaction item depend on this code.
- */
- ec: number;
-
- /**
- * English-only error hint, if available.
- */
- hint?: string;
-
- /**
- * Error details specific to "ec", if applicable/available
- */
- details?: any;
-}
-
-export interface TransactionCommon {
- // opaque unique ID for the transaction, used as a starting point for paginating queries
- // and for invoking actions on the transaction (e.g. deleting/hiding it from the history)
- transactionId: string;
-
- // the type of the transaction; different types might provide additional information
- type: TransactionType;
-
- // main timestamp of the transaction
- timestamp: Timestamp;
-
- // true if the transaction is still pending, false otherwise
- // If a transaction is not longer pending, its timestamp will be updated,
- // but its transactionId will remain unchanged
- pending: boolean;
-
- // Raw amount of the transaction (exclusive of fees or other extra costs)
- amountRaw: AmountString;
-
- // Amount added or removed from the wallet's balance (including all fees and other costs)
- amountEffective: AmountString;
-
- error?: TransactionError;
-}
-
-export type Transaction =
- | TransactionWithdrawal
- | TransactionPayment
- | TransactionRefund
- | TransactionTip
- | TransactionRefresh;
-
-export const enum TransactionType {
- Withdrawal = "withdrawal",
- Payment = "payment",
- Refund = "refund",
- Refresh = "refresh",
- Tip = "tip",
-}
-
-export const enum WithdrawalType {
- TalerBankIntegrationApi = "taler-bank-integration-api",
- ManualTransfer = "manual-transfer",
-}
-
-export type WithdrawalDetails =
- | WithdrawalDetailsForManualTransfer
- | WithdrawalDetailsForTalerBankIntegrationApi;
-
-interface WithdrawalDetailsForManualTransfer {
- type: WithdrawalType.ManualTransfer;
-
- /**
- * Payto URIs that the exchange supports.
- *
- * Already contains the amount and message.
- */
- exchangePaytoUris: string[];
-}
-
-interface WithdrawalDetailsForTalerBankIntegrationApi {
- type: WithdrawalType.TalerBankIntegrationApi;
-
- /**
- * Set to true if the bank has confirmed the withdrawal, false if not.
- * An unconfirmed withdrawal usually requires user-input and should be highlighted in the UI.
- * See also bankConfirmationUrl below.
- */
- confirmed: boolean;
-
- /**
- * If the withdrawal is unconfirmed, this can include a URL for user
- * initiated confirmation.
- */
- bankConfirmationUrl?: string;
-}
-
-// This should only be used for actual withdrawals
-// and not for tips that have their own transactions type.
-interface TransactionWithdrawal extends TransactionCommon {
- type: TransactionType.Withdrawal;
-
- /**
- * Exchange of the withdrawal.
- */
- exchangeBaseUrl: string;
-
- /**
- * Amount that got subtracted from the reserve balance.
- */
- amountRaw: AmountString;
-
- /**
- * Amount that actually was (or will be) added to the wallet's balance.
- */
- amountEffective: AmountString;
-
- withdrawalDetails: WithdrawalDetails;
-}
-
-export const enum PaymentStatus {
- /**
- * Explicitly aborted after timeout / failure
- */
- Aborted = "aborted",
-
- /**
- * Payment failed, wallet will auto-retry.
- * User should be given the option to retry now / abort.
- */
- Failed = "failed",
-
- /**
- * Paid successfully
- */
- Paid = "paid",
-
- /**
- * User accepted, payment is processing.
- */
- Accepted = "accepted",
-}
-
-export interface TransactionPayment extends TransactionCommon {
- type: TransactionType.Payment;
-
- /**
- * Additional information about the payment.
- */
- info: PaymentShortInfo;
-
- /**
- * How far did the wallet get with processing the payment?
- */
- status: PaymentStatus;
-
- /**
- * Amount that must be paid for the contract
- */
- amountRaw: AmountString;
-
- /**
- * Amount that was paid, including deposit, wire and refresh fees.
- */
- amountEffective: AmountString;
-}
-
-interface PaymentShortInfo {
- /**
- * Order ID, uniquely identifies the order within a merchant instance
- */
- orderId: string;
-
- /**
- * More information about the merchant
- */
- merchant: any;
-
- /**
- * Summary of the order, given by the merchant
- */
- summary: string;
-
- /**
- * Map from IETF BCP 47 language tags to localized summaries
- */
- summary_i18n?: { [lang_tag: string]: string };
-
- /**
- * List of products that are part of the order
- */
- products: Product[] | undefined;
-
- /**
- * URL of the fulfillment, given by the merchant
- */
- fulfillmentUrl: string;
-}
-
-interface TransactionRefund extends TransactionCommon {
- type: TransactionType.Refund;
-
- // ID for the transaction that is refunded
- refundedTransactionId: string;
-
- // Additional information about the refunded payment
- info: PaymentShortInfo;
-
- // Part of the refund that couldn't be applied because the refund permissions were expired
- amountInvalid: AmountString;
-
- // Amount that has been refunded by the merchant
- amountRaw: AmountString;
-
- // Amount will be added to the wallet's balance after fees and refreshing
- amountEffective: AmountString;
-}
-
-interface TransactionTip extends TransactionCommon {
- type: TransactionType.Tip;
-
- // true if the user still needs to accept/decline this tip
- waiting: boolean;
-
- // true if the user has accepted this top, false otherwise
- accepted: boolean;
-
- // Exchange that the tip will be (or was) withdrawn from
- exchangeBaseUrl: string;
-
- // More information about the merchant that sent the tip
- merchant: any;
-
- // Raw amount of the tip, without extra fees that apply
- amountRaw: AmountString;
-
- // Amount will be (or was) added to the wallet's balance after fees and refreshing
- amountEffective: AmountString;
-}
-
-// A transaction shown for refreshes that are not associated to other transactions
-// such as a refresh necessary before coin expiration.
-// It should only be returned by the API if the effective amount is different from zero.
-interface TransactionRefresh extends TransactionCommon {
- type: TransactionType.Refresh;
-
- // Exchange that the coins are refreshed with
- exchangeBaseUrl: string;
-
- // Raw amount that is refreshed
- amountRaw: AmountString;
-
- // Amount that will be paid as fees for the refresh
- amountEffective: AmountString;
-}
-
-
-export const codecForTransactionsRequest = (): Codec<TransactionsRequest> =>
- makeCodecForObject<TransactionsRequest>()
- .property("currency", makeCodecOptional(codecForString))
- .property("search", makeCodecOptional(codecForString))
- .build("TransactionsRequest"); \ No newline at end of file
diff --git a/src/types/types-test.ts b/src/types/types-test.ts
deleted file mode 100644
index afdc01844..000000000
--- a/src/types/types-test.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- This file is part of TALER
- (C) 2017 Inria and GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-import test from "ava";
-import { codecForContractTerms } from "./talerTypes";
-
-test("contract terms validation", (t) => {
- const c = {
- nonce: "123123123",
- h_wire: "123",
- amount: "EUR:1.5",
- auditors: [],
- exchanges: [{ master_pub: "foo", url: "foo" }],
- fulfillment_url: "foo",
- max_fee: "EUR:1.5",
- merchant_pub: "12345",
- merchant: { name: "Foo" },
- order_id: "test_order",
- pay_deadline: { t_ms: 42 },
- wire_transfer_deadline: { t_ms: 42 },
- merchant_base_url: "https://example.com/pay",
- products: [],
- refund_deadline: { t_ms: 42 },
- summary: "hello",
- timestamp: { t_ms: 42 },
- wire_method: "test",
- };
-
- codecForContractTerms().decode(c);
-
- const c1 = JSON.parse(JSON.stringify(c));
- c1.pay_deadline = "foo";
-
- try {
- codecForContractTerms().decode(c1);
- } catch (e) {
- t.pass();
- return;
- }
-
- t.fail();
-});
diff --git a/src/types/walletTypes.ts b/src/types/walletTypes.ts
deleted file mode 100644
index 767b4c703..000000000
--- a/src/types/walletTypes.ts
+++ /dev/null
@@ -1,522 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2015-2020 Taler Systems SA
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Types used by clients of the wallet.
- *
- * These types are defined in a separate file make tree shaking easier, since
- * some components use these types (via RPC) but do not depend on the wallet
- * code directly.
- *
- * @author Florian Dold <dold@taler.net>
- */
-
-/**
- * Imports.
- */
-import { AmountJson, codecForAmountJson } from "../util/amounts";
-import * as LibtoolVersion from "../util/libtoolVersion";
-import {
- ExchangeRecord,
- ExchangeWireInfo,
- DenominationSelectionInfo,
-} from "./dbTypes";
-import { Timestamp } from "../util/time";
-import {
- makeCodecForObject,
- codecForString,
- makeCodecOptional,
- Codec,
-} from "../util/codec";
-import { AmountString } from "./talerTypes";
-
-/**
- * Response for the create reserve request to the wallet.
- */
-export class CreateReserveResponse {
- /**
- * Exchange URL where the bank should create the reserve.
- * The URL is canonicalized in the response.
- */
- exchange: string;
-
- /**
- * Reserve public key of the newly created reserve.
- */
- reservePub: string;
-}
-
-/**
- * Information about what will happen when creating a reserve.
- *
- * Sent to the wallet frontend to be rendered and shown to the user.
- */
-export interface ExchangeWithdrawDetails {
- /**
- * Exchange that the reserve will be created at.
- */
- exchangeInfo: ExchangeRecord;
-
- /**
- * Filtered wire info to send to the bank.
- */
- exchangeWireAccounts: string[];
-
- /**
- * Selected denominations for withdraw.
- */
- selectedDenoms: DenominationSelectionInfo;
-
- /**
- * Fees for withdraw.
- */
- withdrawFee: AmountJson;
-
- /**
- * Remaining balance that is too small to be withdrawn.
- */
- overhead: AmountJson;
-
- /**
- * Wire fees from the exchange.
- */
- wireFees: ExchangeWireInfo;
-
- /**
- * Does the wallet know about an auditor for
- * the exchange that the reserve.
- */
- isAudited: boolean;
-
- /**
- * Did the user already accept the current terms of service for the exchange?
- */
- termsOfServiceAccepted: boolean;
-
- /**
- * The exchange is trusted directly.
- */
- isTrusted: boolean;
-
- /**
- * The earliest deposit expiration of the selected coins.
- */
- earliestDepositExpiration: Timestamp;
-
- /**
- * Number of currently offered denominations.
- */
- numOfferedDenoms: number;
-
- /**
- * Public keys of trusted auditors for the currency we're withdrawing.
- */
- trustedAuditorPubs: string[];
-
- /**
- * Result of checking the wallet's version
- * against the exchange's version.
- *
- * Older exchanges don't return version information.
- */
- versionMatch: LibtoolVersion.VersionMatchResult | undefined;
-
- /**
- * Libtool-style version string for the exchange or "unknown"
- * for older exchanges.
- */
- exchangeVersion: string;
-
- /**
- * Libtool-style version string for the wallet.
- */
- walletVersion: string;
-}
-
-
-export interface Balance {
- available: AmountString;
- pendingIncoming: AmountString;
- pendingOutgoing: AmountString;
-
- // Does the balance for this currency have a pending
- // transaction?
- hasPendingTransactions: boolean;
-
- // Is there a pending transaction that would affect the balance
- // and requires user input?
- requiresUserInput: boolean;
-}
-
-export interface BalancesResponse {
- balances: Balance[];
-}
-
-
-/**
- * For terseness.
- */
-export function mkAmount(
- value: number,
- fraction: number,
- currency: string,
-): AmountJson {
- return { value, fraction, currency };
-}
-
-/**
- * Result for confirmPay
- */
-export interface ConfirmPayResult {
- nextUrl: string;
-}
-
-/**
- * Information about all sender wire details known to the wallet,
- * as well as exchanges that accept these wire types.
- */
-export interface SenderWireInfos {
- /**
- * Mapping from exchange base url to list of accepted
- * wire types.
- */
- exchangeWireTypes: { [exchangeBaseUrl: string]: string[] };
-
- /**
- * Sender wire information stored in the wallet.
- */
- senderWires: string[];
-}
-
-/**
- * Request to create a reserve.
- */
-export interface CreateReserveRequest {
- /**
- * The initial amount for the reserve.
- */
- amount: AmountJson;
-
- /**
- * Exchange URL where the bank should create the reserve.
- */
- exchange: string;
-
- /**
- * Payto URI that identifies the exchange's account that the funds
- * for this reserve go into.
- */
- exchangePaytoUri?: string;
-
- /**
- * Wire details (as a payto URI) for the bank account that sent the funds to
- * the exchange.
- */
- senderWire?: string;
-
- /**
- * URL to fetch the withdraw status from the bank.
- */
- bankWithdrawStatusUrl?: string;
-}
-
-export const codecForCreateReserveRequest = (): Codec<CreateReserveRequest> =>
- makeCodecForObject<CreateReserveRequest>()
- .property("amount", codecForAmountJson())
- .property("exchange", codecForString)
- .property("exchangePaytoUri", codecForString)
- .property("senderWire", makeCodecOptional(codecForString))
- .property("bankWithdrawStatusUrl", makeCodecOptional(codecForString))
- .build("CreateReserveRequest");
-
-/**
- * Request to mark a reserve as confirmed.
- */
-export interface ConfirmReserveRequest {
- /**
- * Public key of then reserve that should be marked
- * as confirmed.
- */
- reservePub: string;
-}
-
-export const codecForConfirmReserveRequest = (): Codec<ConfirmReserveRequest> =>
- makeCodecForObject<ConfirmReserveRequest>()
- .property("reservePub", codecForString)
- .build("ConfirmReserveRequest");
-
-/**
- * Wire coins to the user's own bank account.
- */
-export class ReturnCoinsRequest {
- /**
- * The amount to wire.
- */
- amount: AmountJson;
-
- /**
- * The exchange to take the coins from.
- */
- exchange: string;
-
- /**
- * Wire details for the bank account of the customer that will
- * receive the funds.
- */
- senderWire?: string;
-
- /**
- * Verify that a value matches the schema of this class and convert it into a
- * member.
- */
- static checked: (obj: any) => ReturnCoinsRequest;
-}
-
-/**
- * Status of processing a tip.
- */
-export interface TipStatus {
- accepted: boolean;
- amount: AmountJson;
- amountLeft: AmountJson;
- nextUrl: string;
- exchangeUrl: string;
- tipId: string;
- merchantTipId: string;
- merchantOrigin: string;
- expirationTimestamp: Timestamp;
- timestamp: Timestamp;
- totalFees: AmountJson;
-}
-
-export interface BenchmarkResult {
- time: { [s: string]: number };
- repetitions: number;
-}
-
-/**
- * Cached next URL for a particular session id.
- */
-export interface NextUrlResult {
- nextUrl: string;
- lastSessionId: string | undefined;
-}
-
-export const enum PreparePayResultType {
- PaymentPossible = "payment-possible",
- InsufficientBalance = "insufficient-balance",
- AlreadyConfirmed = "already-confirmed",
-}
-
-export type PreparePayResult =
- | PreparePayResultInsufficientBalance
- | PreparePayResultAlreadyConfirmed
- | PreparePayResultPaymentPossible;
-
-export interface PreparePayResultPaymentPossible {
- status: PreparePayResultType.PaymentPossible;
- proposalId: string;
- contractTerms: Record<string, unknown>;
- amountRaw: string;
- amountEffective: string;
-}
-
-export interface PreparePayResultInsufficientBalance {
- status: PreparePayResultType.InsufficientBalance;
- proposalId: string;
- contractTerms: Record<string, unknown>;
-}
-
-export interface PreparePayResultAlreadyConfirmed {
- status: PreparePayResultType.AlreadyConfirmed;
- contractTerms: Record<string, unknown>;
- paid: boolean;
- // Only specified if paid.
- nextUrl?: string;
-}
-
-export interface BankWithdrawDetails {
- selectionDone: boolean;
- transferDone: boolean;
- amount: AmountJson;
- senderWire?: string;
- suggestedExchange?: string;
- confirmTransferUrl?: string;
- wireTypes: string[];
- extractedStatusUrl: string;
-}
-
-export interface AcceptWithdrawalResponse {
- reservePub: string;
- confirmTransferUrl?: string;
-}
-
-/**
- * Details about a purchase, including refund status.
- */
-export interface PurchaseDetails {
- contractTerms: Record<string, undefined>;
- hasRefund: boolean;
- totalRefundAmount: AmountJson;
- totalRefundAndRefreshFees: AmountJson;
-}
-
-export interface WalletDiagnostics {
- walletManifestVersion: string;
- walletManifestDisplayVersion: string;
- errors: string[];
- firefoxIdbProblem: boolean;
- dbOutdated: boolean;
-}
-
-export interface OperationErrorDetails {
- talerErrorCode: number;
- talerErrorHint: string;
- message: string;
- details: unknown;
-}
-
-export interface PlanchetCreationResult {
- coinPub: string;
- coinPriv: string;
- reservePub: string;
- denomPubHash: string;
- denomPub: string;
- blindingKey: string;
- withdrawSig: string;
- coinEv: string;
- coinValue: AmountJson;
- coinEvHash: string;
-}
-
-export interface PlanchetCreationRequest {
- value: AmountJson;
- feeWithdraw: AmountJson;
- denomPub: string;
- reservePub: string;
- reservePriv: string;
-}
-
-/**
- * Reasons for why a coin is being refreshed.
- */
-export const enum RefreshReason {
- Manual = "manual",
- Pay = "pay",
- Refund = "refund",
- AbortPay = "abort-pay",
- Recoup = "recoup",
- BackupRestored = "backup-restored",
-}
-
-/**
- * Wrapper for coin public keys.
- */
-export interface CoinPublicKey {
- readonly coinPub: string;
-}
-
-/**
- * Wrapper for refresh group IDs.
- */
-export interface RefreshGroupId {
- readonly refreshGroupId: string;
-}
-
-/**
- * Private data required to make a deposit permission.
- */
-export interface DepositInfo {
- exchangeBaseUrl: string;
- contractTermsHash: string;
- coinPub: string;
- coinPriv: string;
- spendAmount: AmountJson;
- timestamp: Timestamp;
- refundDeadline: Timestamp;
- merchantPub: string;
- feeDeposit: AmountJson;
- wireInfoHash: string;
- denomPubHash: string;
- denomSig: string;
-}
-
-export interface ExtendedPermissionsResponse {
- newValue: boolean;
-}
-
-export interface ExchangesListRespose {
- exchanges: ExchangeListItem[];
-}
-
-export interface ExchangeListItem {
- exchangeBaseUrl: string;
- currency: string;
- paytoUris: string[];
-}
-
-export interface AcceptManualWithdrawalResult {
- /**
- * Payto URIs that can be used to fund the withdrawal.
- */
- exchangePaytoUris: string[];
-
- /**
- * Public key of the newly created reserve.
- */
- reservePub: string;
-}
-
-export interface ManualWithdrawalDetails {
- /**
- * Did the user accept the current version of the exchange's
- * terms of service?
- */
- tosAccepted: boolean;
-
- /**
- * Amount that the user will transfer to the exchange.
- */
- amountRaw: AmountString;
-
- /**
- * Amount that will be added to the user's wallet balance.
- */
- amountEffective: AmountString;
-
- /**
- * Ways to pay the exchange.
- */
- paytoUris: string[];
-}
-
-export interface GetExchangeTosResult {
- /**
- * Markdown version of the current ToS.
- */
- tos: string;
-
- /**
- * Version tag of the current ToS.
- */
- currentEtag: string;
-
- /**
- * Version tag of the last ToS that the user has accepted,
- * if any.
- */
- acceptedEtag: string | undefined;
-}
diff --git a/src/util/RequestThrottler.ts b/src/util/RequestThrottler.ts
deleted file mode 100644
index d979fbfcf..000000000
--- a/src/util/RequestThrottler.ts
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- 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.
-
- 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/>
- */
-
-/**
- * Implementation of token bucket throttling.
- */
-
-/**
- * Imports.
- */
-import { getTimestampNow, timestampDifference } from "../util/time";
-
-/**
- * Maximum request per second, per origin.
- */
-const MAX_PER_SECOND = 50;
-
-/**
- * Maximum request per minute, per origin.
- */
-const MAX_PER_MINUTE = 100;
-
-/**
- * Maximum request per hour, per origin.
- */
-const MAX_PER_HOUR = 1000;
-
-/**
- * Throttling state for one origin.
- */
-class OriginState {
- private tokensSecond: number = MAX_PER_SECOND;
- private tokensMinute: number = MAX_PER_MINUTE;
- private tokensHour: number = MAX_PER_HOUR;
- private lastUpdate = getTimestampNow();
-
- private refill(): void {
- const now = getTimestampNow();
- const d = timestampDifference(now, this.lastUpdate);
- if (d.d_ms === "forever") {
- throw Error("assertion failed");
- }
- const d_s = d.d_ms / 1000;
- this.tokensSecond = Math.min(
- MAX_PER_SECOND,
- this.tokensSecond + d_s / 1000,
- );
- this.tokensMinute = Math.min(
- MAX_PER_MINUTE,
- this.tokensMinute + (d_s / 1000) * 60,
- );
- this.tokensHour = Math.min(
- MAX_PER_HOUR,
- this.tokensHour + (d_s / 1000) * 60 * 60,
- );
- this.lastUpdate = now;
- }
-
- /**
- * Return true if the request for this origin should be throttled.
- * Otherwise, take a token out of the respective buckets.
- */
- applyThrottle(): boolean {
- this.refill();
- if (this.tokensSecond < 1) {
- console.log("request throttled (per second limit exceeded)");
- return true;
- }
- if (this.tokensMinute < 1) {
- console.log("request throttled (per minute limit exceeded)");
- return true;
- }
- if (this.tokensHour < 1) {
- console.log("request throttled (per hour limit exceeded)");
- return true;
- }
- this.tokensSecond--;
- this.tokensMinute--;
- this.tokensHour--;
- return false;
- }
-}
-
-/**
- * Request throttler, used as a "last layer of defense" when some
- * other part of the re-try logic is broken and we're sending too
- * many requests to the same exchange/bank/merchant.
- */
-export class RequestThrottler {
- private perOriginInfo: { [origin: string]: OriginState } = {};
-
- /**
- * Get the throttling state for an origin, or
- * initialize if no state is associated with the
- * origin yet.
- */
- private getState(origin: string): OriginState {
- const s = this.perOriginInfo[origin];
- if (s) {
- return s;
- }
- const ns = (this.perOriginInfo[origin] = new OriginState());
- return ns;
- }
-
- /**
- * Apply throttling to a request.
- *
- * @returns whether the request should be throttled.
- */
- applyThrottle(requestUrl: string): boolean {
- const origin = new URL(requestUrl).origin;
- return this.getState(origin).applyThrottle();
- }
-}
diff --git a/src/util/amounts-test.ts b/src/util/amounts-test.ts
deleted file mode 100644
index afd8caa51..000000000
--- a/src/util/amounts-test.ts
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2020 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 test from "ava";
-
-import { Amounts, AmountJson } from "../util/amounts";
-
-const jAmt = (
- value: number,
- fraction: number,
- currency: string,
-): AmountJson => ({ value, fraction, currency });
-
-const sAmt = (s: string): AmountJson => Amounts.parseOrThrow(s);
-
-test("amount addition (simple)", (t) => {
- const a1 = jAmt(1, 0, "EUR");
- const a2 = jAmt(1, 0, "EUR");
- const a3 = jAmt(2, 0, "EUR");
- t.true(0 === Amounts.cmp(Amounts.add(a1, a2).amount, a3));
- t.pass();
-});
-
-test("amount addition (saturation)", (t) => {
- const a1 = jAmt(1, 0, "EUR");
- const res = Amounts.add(jAmt(Amounts.maxAmountValue, 0, "EUR"), a1);
- t.true(res.saturated);
- t.pass();
-});
-
-test("amount subtraction (simple)", (t) => {
- const a1 = jAmt(2, 5, "EUR");
- const a2 = jAmt(1, 0, "EUR");
- const a3 = jAmt(1, 5, "EUR");
- t.true(0 === Amounts.cmp(Amounts.sub(a1, a2).amount, a3));
- t.pass();
-});
-
-test("amount subtraction (saturation)", (t) => {
- const a1 = jAmt(0, 0, "EUR");
- const a2 = jAmt(1, 0, "EUR");
- let res = Amounts.sub(a1, a2);
- t.true(res.saturated);
- res = Amounts.sub(a1, a1);
- t.true(!res.saturated);
- t.pass();
-});
-
-test("amount comparison", (t) => {
- t.is(Amounts.cmp(jAmt(1, 0, "EUR"), jAmt(1, 0, "EUR")), 0);
- t.is(Amounts.cmp(jAmt(1, 1, "EUR"), jAmt(1, 0, "EUR")), 1);
- t.is(Amounts.cmp(jAmt(1, 1, "EUR"), jAmt(1, 2, "EUR")), -1);
- t.is(Amounts.cmp(jAmt(1, 0, "EUR"), jAmt(0, 0, "EUR")), 1);
- t.is(Amounts.cmp(jAmt(0, 0, "EUR"), jAmt(1, 0, "EUR")), -1);
- t.is(Amounts.cmp(jAmt(1, 0, "EUR"), jAmt(0, 100000000, "EUR")), 0);
- t.throws(() => Amounts.cmp(jAmt(1, 0, "FOO"), jAmt(1, 0, "BAR")));
- t.pass();
-});
-
-test("amount parsing", (t) => {
- t.is(
- Amounts.cmp(Amounts.parseOrThrow("TESTKUDOS:0"), jAmt(0, 0, "TESTKUDOS")),
- 0,
- );
- t.is(
- Amounts.cmp(Amounts.parseOrThrow("TESTKUDOS:10"), jAmt(10, 0, "TESTKUDOS")),
- 0,
- );
- t.is(
- Amounts.cmp(
- Amounts.parseOrThrow("TESTKUDOS:0.1"),
- jAmt(0, 10000000, "TESTKUDOS"),
- ),
- 0,
- );
- t.is(
- Amounts.cmp(
- Amounts.parseOrThrow("TESTKUDOS:0.00000001"),
- jAmt(0, 1, "TESTKUDOS"),
- ),
- 0,
- );
- t.is(
- Amounts.cmp(
- Amounts.parseOrThrow("TESTKUDOS:4503599627370496.99999999"),
- jAmt(4503599627370496, 99999999, "TESTKUDOS"),
- ),
- 0,
- );
- t.throws(() => Amounts.parseOrThrow("foo:"));
- t.throws(() => Amounts.parseOrThrow("1.0"));
- t.throws(() => Amounts.parseOrThrow("42"));
- t.throws(() => Amounts.parseOrThrow(":1.0"));
- t.throws(() => Amounts.parseOrThrow(":42"));
- t.throws(() => Amounts.parseOrThrow("EUR:.42"));
- t.throws(() => Amounts.parseOrThrow("EUR:42."));
- t.throws(() => Amounts.parseOrThrow("TESTKUDOS:4503599627370497.99999999"));
- t.is(
- Amounts.cmp(
- Amounts.parseOrThrow("TESTKUDOS:0.99999999"),
- jAmt(0, 99999999, "TESTKUDOS"),
- ),
- 0,
- );
- t.throws(() => Amounts.parseOrThrow("TESTKUDOS:0.999999991"));
- t.pass();
-});
-
-test("amount stringification", (t) => {
- t.is(Amounts.stringify(jAmt(0, 0, "TESTKUDOS")), "TESTKUDOS:0");
- t.is(Amounts.stringify(jAmt(4, 94000000, "TESTKUDOS")), "TESTKUDOS:4.94");
- t.is(Amounts.stringify(jAmt(0, 10000000, "TESTKUDOS")), "TESTKUDOS:0.1");
- t.is(Amounts.stringify(jAmt(0, 1, "TESTKUDOS")), "TESTKUDOS:0.00000001");
- t.is(Amounts.stringify(jAmt(5, 0, "TESTKUDOS")), "TESTKUDOS:5");
- // denormalized
- t.is(Amounts.stringify(jAmt(1, 100000000, "TESTKUDOS")), "TESTKUDOS:2");
- t.pass();
-});
-
-test("amount multiplication", (t) => {
- t.is(Amounts.stringify(Amounts.mult(sAmt("EUR:1.11"), 0).amount), "EUR:0");
- t.is(Amounts.stringify(Amounts.mult(sAmt("EUR:1.11"), 1).amount), "EUR:1.11");
- t.is(Amounts.stringify(Amounts.mult(sAmt("EUR:1.11"), 2).amount), "EUR:2.22");
- t.is(Amounts.stringify(Amounts.mult(sAmt("EUR:1.11"), 3).amount), "EUR:3.33");
- t.is(Amounts.stringify(Amounts.mult(sAmt("EUR:1.11"), 4).amount), "EUR:4.44");
- t.is(Amounts.stringify(Amounts.mult(sAmt("EUR:1.11"), 5).amount), "EUR:5.55");
-});
diff --git a/src/util/amounts.ts b/src/util/amounts.ts
deleted file mode 100644
index 1e7f192f4..000000000
--- a/src/util/amounts.ts
+++ /dev/null
@@ -1,383 +0,0 @@
-/*
- 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/>
- */
-
-/**
- * Types and helper functions for dealing with Taler amounts.
- */
-
-/**
- * Imports.
- */
-import {
- makeCodecForObject,
- codecForString,
- codecForNumber,
- Codec,
-} from "./codec";
-
-/**
- * Number of fractional units that one value unit represents.
- */
-export const fractionalBase = 1e8;
-
-/**
- * How many digits behind the comma are required to represent the
- * fractional value in human readable decimal format? Must match
- * lg(fractionalBase)
- */
-export const fractionalLength = 8;
-
-/**
- * Maximum allowed value field of an amount.
- */
-export const maxAmountValue = 2 ** 52;
-
-/**
- * Non-negative financial amount. Fractional values are expressed as multiples
- * of 1e-8.
- */
-export interface AmountJson {
- /**
- * Value, must be an integer.
- */
- readonly value: number;
-
- /**
- * Fraction, must be an integer. Represent 1/1e8 of a unit.
- */
- readonly fraction: number;
-
- /**
- * Currency of the amount.
- */
- readonly currency: string;
-}
-
-export const codecForAmountJson = (): Codec<AmountJson> =>
- makeCodecForObject<AmountJson>()
- .property("currency", codecForString)
- .property("value", codecForNumber)
- .property("fraction", codecForNumber)
- .build("AmountJson");
-
-/**
- * Result of a possibly overflowing operation.
- */
-export interface Result {
- /**
- * Resulting, possibly saturated amount.
- */
- amount: AmountJson;
- /**
- * Was there an over-/underflow?
- */
- saturated: boolean;
-}
-
-/**
- * Get an amount that represents zero units of a currency.
- */
-export function getZero(currency: string): AmountJson {
- return {
- currency,
- fraction: 0,
- value: 0,
- };
-}
-
-export function sum(amounts: AmountJson[]): Result {
- if (amounts.length <= 0) {
- throw Error("can't sum zero amounts");
- }
- return add(amounts[0], ...amounts.slice(1));
-}
-
-/**
- * Add two amounts. Return the result and whether
- * the addition overflowed. The overflow is always handled
- * by saturating and never by wrapping.
- *
- * Throws when currencies don't match.
- */
-export function add(first: AmountJson, ...rest: AmountJson[]): Result {
- const currency = first.currency;
- let value = first.value + Math.floor(first.fraction / fractionalBase);
- if (value > maxAmountValue) {
- return {
- amount: { currency, value: maxAmountValue, fraction: fractionalBase - 1 },
- saturated: true,
- };
- }
- let fraction = first.fraction % fractionalBase;
- for (const x of rest) {
- if (x.currency !== currency) {
- throw Error(`Mismatched currency: ${x.currency} and ${currency}`);
- }
-
- value =
- value + x.value + Math.floor((fraction + x.fraction) / fractionalBase);
- fraction = Math.floor((fraction + x.fraction) % fractionalBase);
- if (value > maxAmountValue) {
- return {
- amount: {
- currency,
- value: maxAmountValue,
- fraction: fractionalBase - 1,
- },
- saturated: true,
- };
- }
- }
- return { amount: { currency, value, fraction }, saturated: false };
-}
-
-/**
- * Subtract two amounts. Return the result and whether
- * the subtraction overflowed. The overflow is always handled
- * by saturating and never by wrapping.
- *
- * Throws when currencies don't match.
- */
-export function sub(a: AmountJson, ...rest: AmountJson[]): Result {
- const currency = a.currency;
- let value = a.value;
- let fraction = a.fraction;
-
- for (const b of rest) {
- if (b.currency !== currency) {
- throw Error(`Mismatched currency: ${b.currency} and ${currency}`);
- }
- if (fraction < b.fraction) {
- if (value < 1) {
- return { amount: { currency, value: 0, fraction: 0 }, saturated: true };
- }
- value--;
- fraction += fractionalBase;
- }
- console.assert(fraction >= b.fraction);
- fraction -= b.fraction;
- if (value < b.value) {
- return { amount: { currency, value: 0, fraction: 0 }, saturated: true };
- }
- value -= b.value;
- }
-
- return { amount: { currency, value, fraction }, saturated: false };
-}
-
-/**
- * Compare two amounts. Returns 0 when equal, -1 when a < b
- * and +1 when a > b. Throws when currencies don't match.
- */
-export function cmp(a: AmountJson, b: AmountJson): -1 | 0 | 1 {
- if (a.currency !== b.currency) {
- throw Error(`Mismatched currency: ${a.currency} and ${b.currency}`);
- }
- const av = a.value + Math.floor(a.fraction / fractionalBase);
- const af = a.fraction % fractionalBase;
- const bv = b.value + Math.floor(b.fraction / fractionalBase);
- const bf = b.fraction % fractionalBase;
- switch (true) {
- case av < bv:
- return -1;
- case av > bv:
- return 1;
- case af < bf:
- return -1;
- case af > bf:
- return 1;
- case af === bf:
- return 0;
- default:
- throw Error("assertion failed");
- }
-}
-
-/**
- * Create a copy of an amount.
- */
-export function copy(a: AmountJson): AmountJson {
- return {
- currency: a.currency,
- fraction: a.fraction,
- value: a.value,
- };
-}
-
-/**
- * Divide an amount. Throws on division by zero.
- */
-export function divide(a: AmountJson, n: number): AmountJson {
- if (n === 0) {
- throw Error(`Division by 0`);
- }
- if (n === 1) {
- return { value: a.value, fraction: a.fraction, currency: a.currency };
- }
- const r = a.value % n;
- return {
- currency: a.currency,
- fraction: Math.floor((r * fractionalBase + a.fraction) / n),
- value: Math.floor(a.value / n),
- };
-}
-
-/**
- * Check if an amount is non-zero.
- */
-export function isNonZero(a: AmountJson): boolean {
- return a.value > 0 || a.fraction > 0;
-}
-
-export function isZero(a: AmountJson): boolean {
- return a.value === 0 && a.fraction === 0;
-}
-
-/**
- * Parse an amount like 'EUR:20.5' for 20 Euros and 50 ct.
- */
-export function parse(s: string): AmountJson | undefined {
- const res = s.match(/^([a-zA-Z0-9_*-]+):([0-9]+)([.][0-9]+)?$/);
- if (!res) {
- return undefined;
- }
- const tail = res[3] || ".0";
- if (tail.length > fractionalLength + 1) {
- return undefined;
- }
- const value = Number.parseInt(res[2]);
- if (value > maxAmountValue) {
- return undefined;
- }
- return {
- currency: res[1],
- fraction: Math.round(fractionalBase * Number.parseFloat(tail)),
- value,
- };
-}
-
-/**
- * Parse amount in standard string form (like 'EUR:20.5'),
- * throw if the input is not a valid amount.
- */
-export function parseOrThrow(s: string): AmountJson {
- const res = parse(s);
- if (!res) {
- throw Error(`Can't parse amount: "${s}"`);
- }
- return res;
-}
-
-/**
- * Convert a float to a Taler amount.
- * Loss of precision possible.
- */
-export function fromFloat(floatVal: number, currency: string): AmountJson {
- return {
- currency,
- fraction: Math.floor((floatVal - Math.floor(floatVal)) * fractionalBase),
- value: Math.floor(floatVal),
- };
-}
-
-/**
- * Convert to standard human-readable string representation that's
- * also used in JSON formats.
- */
-export function stringify(a: AmountJson): string {
- const av = a.value + Math.floor(a.fraction / fractionalBase);
- const af = a.fraction % fractionalBase;
- let s = av.toString();
-
- if (af) {
- s = s + ".";
- let n = af;
- for (let i = 0; i < fractionalLength; i++) {
- if (!n) {
- break;
- }
- s = s + Math.floor((n / fractionalBase) * 10).toString();
- n = (n * 10) % fractionalBase;
- }
- }
-
- return `${a.currency}:${s}`;
-}
-
-/**
- * Check if the argument is a valid amount in string form.
- */
-function check(a: any): boolean {
- if (typeof a !== "string") {
- return false;
- }
- try {
- const parsedAmount = parse(a);
- return !!parsedAmount;
- } catch {
- return false;
- }
-}
-
-function mult(a: AmountJson, n: number): Result {
- if (!Number.isInteger(n)) {
- throw Error("amount can only be multipied by an integer");
- }
- if (n < 0) {
- throw Error("amount can only be multiplied by a positive integer");
- }
- if (n == 0) {
- return { amount: getZero(a.currency), saturated: false };
- }
- let x = a;
- let acc = getZero(a.currency);
- while (n > 1) {
- if (n % 2 == 0) {
- n = n / 2;
- } else {
- n = (n - 1) / 2;
- const r2 = add(acc, x);
- if (r2.saturated) {
- return r2;
- }
- acc = r2.amount;
- }
- const r2 = add(x, x);
- if (r2.saturated) {
- return r2;
- }
- x = r2.amount;
- }
- return add(acc, x);
-}
-
-// Export all amount-related functions here for better IDE experience.
-export const Amounts = {
- stringify: stringify,
- parse: parse,
- parseOrThrow: parseOrThrow,
- cmp: cmp,
- add: add,
- sum: sum,
- sub: sub,
- mult: mult,
- check: check,
- getZero: getZero,
- isZero: isZero,
- maxAmountValue: maxAmountValue,
- fromFloat: fromFloat,
- copy: copy,
-};
diff --git a/src/util/assertUnreachable.ts b/src/util/assertUnreachable.ts
deleted file mode 100644
index ffdf88f04..000000000
--- a/src/util/assertUnreachable.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- 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/>
- */
-
-export function assertUnreachable(x: never): never {
- throw new Error("Didn't expect to get here");
-}
diff --git a/src/util/asyncMemo.ts b/src/util/asyncMemo.ts
deleted file mode 100644
index 6e88081b6..000000000
--- a/src/util/asyncMemo.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- 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/>
- */
-
-interface MemoEntry<T> {
- p: Promise<T>;
- t: number;
- n: number;
-}
-
-export class AsyncOpMemoMap<T> {
- private n = 0;
- private memoMap: { [k: string]: MemoEntry<T> } = {};
-
- private cleanUp(key: string, n: number): void {
- const r = this.memoMap[key];
- if (r && r.n === n) {
- delete this.memoMap[key];
- }
- }
-
- memo(key: string, pg: () => Promise<T>): Promise<T> {
- const res = this.memoMap[key];
- if (res) {
- return res.p;
- }
- const n = this.n++;
- // Wrap the operation in case it immediately throws
- const p = Promise.resolve().then(() => pg());
- this.memoMap[key] = {
- p,
- n,
- t: new Date().getTime(),
- };
- return p.finally(() => {
- this.cleanUp(key, n);
- });
- }
- clear(): void {
- this.memoMap = {};
- }
-}
-
-export class AsyncOpMemoSingle<T> {
- private n = 0;
- private memoEntry: MemoEntry<T> | undefined;
-
- private cleanUp(n: number): void {
- if (this.memoEntry && this.memoEntry.n === n) {
- this.memoEntry = undefined;
- }
- }
-
- memo(pg: () => Promise<T>): Promise<T> {
- const res = this.memoEntry;
- if (res) {
- return res.p;
- }
- const n = this.n++;
- // Wrap the operation in case it immediately throws
- const p = Promise.resolve().then(() => pg());
- p.finally(() => {
- this.cleanUp(n);
- });
- this.memoEntry = {
- p,
- n,
- t: new Date().getTime(),
- };
- return p;
- }
- clear(): void {
- this.memoEntry = undefined;
- }
-}
diff --git a/src/util/codec-test.ts b/src/util/codec-test.ts
deleted file mode 100644
index b429c318c..000000000
--- a/src/util/codec-test.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2018-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/>
- */
-
-/**
- * Type-safe codecs for converting from/to JSON.
- */
-
-import test from "ava";
-import {
- Codec,
- makeCodecForObject,
- makeCodecForConstString,
- codecForString,
- makeCodecForUnion,
-} from "./codec";
-
-interface MyObj {
- foo: string;
-}
-
-interface AltOne {
- type: "one";
- foo: string;
-}
-
-interface AltTwo {
- type: "two";
- bar: string;
-}
-
-type MyUnion = AltOne | AltTwo;
-
-test("basic codec", (t) => {
- const myObjCodec = makeCodecForObject<MyObj>()
- .property("foo", codecForString)
- .build("MyObj");
- const res = myObjCodec.decode({ foo: "hello" });
- t.assert(res.foo === "hello");
-
- t.throws(() => {
- myObjCodec.decode({ foo: 123 });
- });
-});
-
-test("union", (t) => {
- const altOneCodec: Codec<AltOne> = makeCodecForObject<AltOne>()
- .property("type", makeCodecForConstString("one"))
- .property("foo", codecForString)
- .build("AltOne");
- const altTwoCodec: Codec<AltTwo> = makeCodecForObject<AltTwo>()
- .property("type", makeCodecForConstString("two"))
- .property("bar", codecForString)
- .build("AltTwo");
- const myUnionCodec: Codec<MyUnion> = makeCodecForUnion<MyUnion>()
- .discriminateOn("type")
- .alternative("one", altOneCodec)
- .alternative("two", altTwoCodec)
- .build<MyUnion>("MyUnion");
-
- const res = myUnionCodec.decode({ type: "one", foo: "bla" });
- t.is(res.type, "one");
- if (res.type == "one") {
- t.is(res.foo, "bla");
- }
-});
diff --git a/src/util/codec.ts b/src/util/codec.ts
deleted file mode 100644
index 383a2d99e..000000000
--- a/src/util/codec.ts
+++ /dev/null
@@ -1,410 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2018-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/>
- */
-
-/**
- * Type-safe codecs for converting from/to JSON.
- */
-
- /* eslint-disable @typescript-eslint/ban-types */
-
-/**
- * Error thrown when decoding fails.
- */
-export class DecodingError extends Error {
- constructor(message: string) {
- super(message);
- Object.setPrototypeOf(this, DecodingError.prototype);
- this.name = "DecodingError";
- }
-}
-
-/**
- * Context information to show nicer error messages when decoding fails.
- */
-export interface Context {
- readonly path?: string[];
-}
-
-export function renderContext(c?: Context): string {
- const p = c?.path;
- if (p) {
- return p.join(".");
- } else {
- return "(unknown)";
- }
-}
-
-function joinContext(c: Context | undefined, part: string): Context {
- const path = c?.path ?? [];
- return {
- path: path.concat([part]),
- };
-}
-
-/**
- * A codec converts untyped JSON to a typed object.
- */
-export interface Codec<V> {
- /**
- * Decode untyped JSON to an object of type [[V]].
- */
- readonly decode: (x: any, c?: Context) => V;
-}
-
-type SingletonRecord<K extends keyof any, V> = { [Y in K]: V };
-
-interface Prop {
- name: string;
- codec: Codec<any>;
-}
-
-interface Alternative {
- tagValue: any;
- codec: Codec<any>;
-}
-
-class ObjectCodecBuilder<OutputType, PartialOutputType> {
- private propList: Prop[] = [];
-
- /**
- * Define a property for the object.
- */
- property<K extends keyof OutputType & string, V extends OutputType[K]>(
- x: K,
- codec: Codec<V>,
- ): ObjectCodecBuilder<OutputType, PartialOutputType & SingletonRecord<K, V>> {
- if (!codec) {
- throw Error("inner codec must be defined");
- }
- this.propList.push({ name: x, codec: codec });
- return this as any;
- }
-
- /**
- * Return the built codec.
- *
- * @param objectDisplayName name of the object that this codec operates on,
- * used in error messages.
- */
- build(objectDisplayName: string): Codec<PartialOutputType> {
- const propList = this.propList;
- return {
- decode(x: any, c?: Context): PartialOutputType {
- if (!c) {
- c = {
- path: [`(${objectDisplayName})`],
- };
- }
- if (typeof x !== "object") {
- throw new DecodingError(
- `expected object for ${objectDisplayName} at ${renderContext(
- c,
- )} but got ${typeof x}`,
- );
- }
- const obj: any = {};
- for (const prop of propList) {
- const propRawVal = x[prop.name];
- const propVal = prop.codec.decode(
- propRawVal,
- joinContext(c, prop.name),
- );
- obj[prop.name] = propVal;
- }
- return obj as PartialOutputType;
- },
- };
- }
-}
-
-class UnionCodecBuilder<
- TargetType,
- TagPropertyLabel extends keyof TargetType,
- CommonBaseType,
- PartialTargetType
-> {
- private alternatives = new Map<any, Alternative>();
-
- constructor(
- private discriminator: TagPropertyLabel,
- private baseCodec?: Codec<CommonBaseType>,
- ) {}
-
- /**
- * Define a property for the object.
- */
- alternative<V>(
- tagValue: TargetType[TagPropertyLabel],
- codec: Codec<V>,
- ): UnionCodecBuilder<
- TargetType,
- TagPropertyLabel,
- CommonBaseType,
- PartialTargetType | V
- > {
- if (!codec) {
- throw Error("inner codec must be defined");
- }
- this.alternatives.set(tagValue, { codec, tagValue });
- return this as any;
- }
-
- /**
- * Return the built codec.
- *
- * @param objectDisplayName name of the object that this codec operates on,
- * used in error messages.
- */
- build<R extends PartialTargetType & CommonBaseType = never>(
- objectDisplayName: string,
- ): Codec<R> {
- const alternatives = this.alternatives;
- const discriminator = this.discriminator;
- const baseCodec = this.baseCodec;
- return {
- decode(x: any, c?: Context): R {
- if (!c) {
- c = {
- path: [`(${objectDisplayName})`],
- };
- }
- const d = x[discriminator];
- if (d === undefined) {
- throw new DecodingError(
- `expected tag for ${objectDisplayName} at ${renderContext(
- c,
- )}.${discriminator}`,
- );
- }
- const alt = alternatives.get(d);
- if (!alt) {
- throw new DecodingError(
- `unknown tag for ${objectDisplayName} ${d} at ${renderContext(
- c,
- )}.${discriminator}`,
- );
- }
- const altDecoded = alt.codec.decode(x);
- if (baseCodec) {
- const baseDecoded = baseCodec.decode(x, c);
- return { ...baseDecoded, ...altDecoded };
- } else {
- return altDecoded;
- }
- },
- };
- }
-}
-
-export class UnionCodecPreBuilder<T> {
- discriminateOn<D extends keyof T, B = {}>(
- discriminator: D,
- baseCodec?: Codec<B>,
- ): UnionCodecBuilder<T, D, B, never> {
- return new UnionCodecBuilder<T, D, B, never>(discriminator, baseCodec);
- }
-}
-
-/**
- * Return a builder for a codec that decodes an object with properties.
- */
-export function makeCodecForObject<T>(): ObjectCodecBuilder<T, {}> {
- return new ObjectCodecBuilder<T, {}>();
-}
-
-export function makeCodecForUnion<T>(): UnionCodecPreBuilder<T> {
- return new UnionCodecPreBuilder<T>();
-}
-
-/**
- * Return a codec for a mapping from a string to values described by the inner codec.
- */
-export function makeCodecForMap<T>(
- innerCodec: Codec<T>,
-): Codec<{ [x: string]: T }> {
- if (!innerCodec) {
- throw Error("inner codec must be defined");
- }
- return {
- decode(x: any, c?: Context): { [x: string]: T } {
- const map: { [x: string]: T } = {};
- if (typeof x !== "object") {
- throw new DecodingError(`expected object at ${renderContext(c)}`);
- }
- for (const i in x) {
- map[i] = innerCodec.decode(x[i], joinContext(c, `[${i}]`));
- }
- return map;
- },
- };
-}
-
-/**
- * Return a codec for a list, containing values described by the inner codec.
- */
-export function makeCodecForList<T>(innerCodec: Codec<T>): Codec<T[]> {
- if (!innerCodec) {
- throw Error("inner codec must be defined");
- }
- return {
- decode(x: any, c?: Context): T[] {
- const arr: T[] = [];
- if (!Array.isArray(x)) {
- throw new DecodingError(`expected array at ${renderContext(c)}`);
- }
- for (const i in x) {
- arr.push(innerCodec.decode(x[i], joinContext(c, `[${i}]`)));
- }
- return arr;
- },
- };
-}
-
-/**
- * Return a codec for a value that must be a number.
- */
-export const codecForNumber: Codec<number> = {
- decode(x: any, c?: Context): number {
- if (typeof x === "number") {
- return x;
- }
- throw new DecodingError(
- `expected number at ${renderContext(c)} but got ${typeof x}`,
- );
- },
-};
-
-/**
- * Return a codec for a value that must be a number.
- */
-export const codecForBoolean: Codec<boolean> = {
- decode(x: any, c?: Context): boolean {
- if (typeof x === "boolean") {
- return x;
- }
- throw new DecodingError(
- `expected boolean at ${renderContext(c)} but got ${typeof x}`,
- );
- },
-};
-
-/**
- * Return a codec for a value that must be a string.
- */
-export const codecForString: Codec<string> = {
- decode(x: any, c?: Context): string {
- if (typeof x === "string") {
- return x;
- }
- throw new DecodingError(
- `expected string at ${renderContext(c)} but got ${typeof x}`,
- );
- },
-};
-
-/**
- * Codec that allows any value.
- */
-export const codecForAny: Codec<any> = {
- decode(x: any, c?: Context): any {
- return x;
- },
-};
-
-/**
- * Return a codec for a value that must be a string.
- */
-export function makeCodecForConstString<V extends string>(s: V): Codec<V> {
- return {
- decode(x: any, c?: Context): V {
- if (x === s) {
- return x;
- }
- throw new DecodingError(
- `expected string constant "${s}" at ${renderContext(
- c,
- )} but got ${typeof x}`,
- );
- },
- };
-}
-
-/**
- * Return a codec for a boolean true constant.
- */
-export function makeCodecForConstTrue(): Codec<true> {
- return {
- decode(x: any, c?: Context): true {
- if (x === true) {
- return x;
- }
- throw new DecodingError(
- `expected boolean true at ${renderContext(
- c,
- )} but got ${typeof x}`,
- );
- },
- };
-}
-
-/**
- * Return a codec for a boolean true constant.
- */
-export function makeCodecForConstFalse(): Codec<false> {
- return {
- decode(x: any, c?: Context): false {
- if (x === false) {
- return x;
- }
- throw new DecodingError(
- `expected boolean false at ${renderContext(
- c,
- )} but got ${typeof x}`,
- );
- },
- };
-}
-
-/**
- * Return a codec for a value that must be a constant number.
- */
-export function makeCodecForConstNumber<V extends number>(n: V): Codec<V> {
- return {
- decode(x: any, c?: Context): V {
- if (x === n) {
- return x;
- }
- throw new DecodingError(
- `expected number constant "${n}" at ${renderContext(
- c,
- )} but got ${typeof x}`,
- );
- },
- };
-}
-
-export function makeCodecOptional<V>(
- innerCodec: Codec<V>,
-): Codec<V | undefined> {
- return {
- decode(x: any, c?: Context): V | undefined {
- if (x === undefined || x === null) {
- return undefined;
- }
- return innerCodec.decode(x, c);
- },
- };
-}
diff --git a/src/util/helpers-test.ts b/src/util/helpers-test.ts
deleted file mode 100644
index dbecf14b8..000000000
--- a/src/util/helpers-test.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- This file is part of TALER
- (C) 2017 Inria and GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-import test from "ava";
-import * as helpers from "./helpers";
-
-test("URL canonicalization", (t) => {
- // converts to relative, adds https
- t.is(
- "https://alice.example.com/exchange/",
- helpers.canonicalizeBaseUrl("alice.example.com/exchange"),
- );
-
- // keeps http, adds trailing slash
- t.is(
- "http://alice.example.com/exchange/",
- helpers.canonicalizeBaseUrl("http://alice.example.com/exchange"),
- );
-
- // keeps http, adds trailing slash
- t.is(
- "http://alice.example.com/exchange/",
- helpers.canonicalizeBaseUrl("http://alice.example.com/exchange#foobar"),
- );
-
- // Remove search component
- t.is(
- "http://alice.example.com/exchange/",
- helpers.canonicalizeBaseUrl("http://alice.example.com/exchange?foo=bar"),
- );
-
- t.pass();
-});
diff --git a/src/util/helpers.ts b/src/util/helpers.ts
deleted file mode 100644
index 7cd9e4234..000000000
--- a/src/util/helpers.ts
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Small helper functions that don't fit anywhere else.
- */
-
-/**
- * Imports.
- */
-import { AmountJson } from "./amounts";
-import * as Amounts from "./amounts";
-
-/**
- * Show an amount in a form suitable for the user.
- * FIXME: In the future, this should consider currency-specific
- * settings such as significant digits or currency symbols.
- */
-export function amountToPretty(amount: AmountJson): string {
- const x = amount.value + amount.fraction / Amounts.fractionalBase;
- return `${x} ${amount.currency}`;
-}
-
-/**
- * Canonicalize a base url, typically for the exchange.
- *
- * See http://api.taler.net/wallet.html#general
- */
-export function canonicalizeBaseUrl(url: string): string {
- if (!url.startsWith("http") && !url.startsWith("https")) {
- url = "https://" + url;
- }
- const x = new URL(url);
- if (!x.pathname.endsWith("/")) {
- x.pathname = x.pathname + "/";
- }
- x.search = "";
- x.hash = "";
- return x.href;
-}
-
-/**
- * Convert object to JSON with canonical ordering of keys
- * and whitespace omitted.
- */
-export function canonicalJson(obj: any): string {
- // Check for cycles, etc.
- JSON.stringify(obj);
- if (typeof obj === "string" || typeof obj === "number" || obj === null) {
- return JSON.stringify(obj);
- }
- if (Array.isArray(obj)) {
- const objs: string[] = obj.map((e) => canonicalJson(e));
- return `[${objs.join(",")}]`;
- }
- const keys: string[] = [];
- for (const key in obj) {
- keys.push(key);
- }
- keys.sort();
- let s = "{";
- for (let i = 0; i < keys.length; i++) {
- const key = keys[i];
- s += JSON.stringify(key) + ":" + canonicalJson(obj[key]);
- if (i !== keys.length - 1) {
- s += ",";
- }
- }
- return s + "}";
-}
-
-/**
- * Check for deep equality of two objects.
- * Only arrays, objects and primitives are supported.
- */
-export function deepEquals(x: any, y: any): boolean {
- if (x === y) {
- return true;
- }
-
- if (Array.isArray(x) && x.length !== y.length) {
- return false;
- }
-
- const p = Object.keys(x);
- return (
- Object.keys(y).every((i) => p.indexOf(i) !== -1) &&
- p.every((i) => deepEquals(x[i], y[i]))
- );
-}
-
-export function deepCopy(x: any): any {
- // FIXME: this has many issues ...
- return JSON.parse(JSON.stringify(x));
-}
-
-/**
- * Map from a collection to a list or results and then
- * concatenate the results.
- */
-export function flatMap<T, U>(xs: T[], f: (x: T) => U[]): U[] {
- return xs.reduce((acc: U[], next: T) => [...f(next), ...acc], []);
-}
-
-/**
- * Compute the hash function of a JSON object.
- */
-export function hash(val: any): number {
- const str = canonicalJson(val);
- // https://github.com/darkskyapp/string-hash
- let h = 5381;
- let i = str.length;
- while (i) {
- h = (h * 33) ^ str.charCodeAt(--i);
- }
-
- /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
- * integers. Since we want the results to be always positive, convert the
- * signed int to an unsigned by doing an unsigned bitshift. */
- return h >>> 0;
-}
-
-/**
- * Lexically compare two strings.
- */
-export function strcmp(s1: string, s2: string): number {
- if (s1 < s2) {
- return -1;
- }
- if (s1 > s2) {
- return 1;
- }
- return 0;
-}
diff --git a/src/util/http.ts b/src/util/http.ts
deleted file mode 100644
index 38892491b..000000000
--- a/src/util/http.ts
+++ /dev/null
@@ -1,362 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Helpers for doing XMLHttpRequest-s that are based on ES6 promises.
- * Allows for easy mocking for test cases.
- */
-
-/**
- * Imports
- */
-import { Codec } from "./codec";
-import { OperationFailedError, makeErrorDetails } from "../operations/errors";
-import { TalerErrorCode } from "../TalerErrorCode";
-import { Logger } from "./logging";
-
-const logger = new Logger("http.ts");
-
-/**
- * An HTTP response that is returned by all request methods of this library.
- */
-export interface HttpResponse {
- requestUrl: string;
- status: number;
- headers: Headers;
- json(): Promise<any>;
- text(): Promise<string>;
-}
-
-export interface HttpRequestOptions {
- headers?: { [name: string]: string };
-}
-
-export enum HttpResponseStatus {
- Ok = 200,
- Gone = 210,
-}
-
-/**
- * Headers, roughly modeled after the fetch API's headers object.
- */
-export class Headers {
- private headerMap = new Map<string, string>();
-
- get(name: string): string | null {
- const r = this.headerMap.get(name.toLowerCase());
- if (r) {
- return r;
- }
- return null;
- }
-
- set(name: string, value: string): void {
- const normalizedName = name.toLowerCase();
- const existing = this.headerMap.get(normalizedName);
- if (existing !== undefined) {
- this.headerMap.set(normalizedName, existing + "," + value);
- } else {
- this.headerMap.set(normalizedName, value);
- }
- }
-}
-
-/**
- * Interface for the HTTP request library used by the wallet.
- *
- * The request library is bundled into an interface to make mocking and
- * request tunneling easy.
- */
-export interface HttpRequestLibrary {
- /**
- * Make an HTTP GET request.
- */
- get(url: string, opt?: HttpRequestOptions): Promise<HttpResponse>;
-
- /**
- * Make an HTTP POST request with a JSON body.
- */
- postJson(
- url: string,
- body: any,
- opt?: HttpRequestOptions,
- ): Promise<HttpResponse>;
-}
-
-/**
- * An implementation of the [[HttpRequestLibrary]] using the
- * browser's XMLHttpRequest.
- */
-export class BrowserHttpLib implements HttpRequestLibrary {
- private req(
- method: string,
- url: string,
- requestBody?: any,
- options?: HttpRequestOptions,
- ): Promise<HttpResponse> {
- return new Promise<HttpResponse>((resolve, reject) => {
- const myRequest = new XMLHttpRequest();
- myRequest.open(method, url);
- if (options?.headers) {
- for (const headerName in options.headers) {
- myRequest.setRequestHeader(headerName, options.headers[headerName]);
- }
- }
- myRequest.setRequestHeader;
- if (requestBody) {
- myRequest.send(requestBody);
- } else {
- myRequest.send();
- }
-
- myRequest.onerror = (e) => {
- logger.error("http request error");
- reject(
- OperationFailedError.fromCode(
- TalerErrorCode.WALLET_NETWORK_ERROR,
- "Could not make request",
- {
- requestUrl: url,
- },
- ),
- );
- };
-
- myRequest.addEventListener("readystatechange", (e) => {
- if (myRequest.readyState === XMLHttpRequest.DONE) {
- if (myRequest.status === 0) {
- const exc = OperationFailedError.fromCode(
- TalerErrorCode.WALLET_NETWORK_ERROR,
- "HTTP request failed (status 0, maybe URI scheme was wrong?)",
- {
- requestUrl: url,
- },
- );
- reject(exc);
- return;
- }
- const makeJson = async (): Promise<any> => {
- let responseJson;
- try {
- responseJson = JSON.parse(myRequest.responseText);
- } catch (e) {
- throw OperationFailedError.fromCode(
- TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE,
- "Invalid JSON from HTTP response",
- {
- requestUrl: url,
- httpStatusCode: myRequest.status,
- },
- );
- }
- if (responseJson === null || typeof responseJson !== "object") {
- throw OperationFailedError.fromCode(
- TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE,
- "Invalid JSON from HTTP response",
- {
- requestUrl: url,
- httpStatusCode: myRequest.status,
- },
- );
- }
- return responseJson;
- };
-
- const headers = myRequest.getAllResponseHeaders();
- const arr = headers.trim().split(/[\r\n]+/);
-
- // Create a map of header names to values
- const headerMap = new Headers();
- arr.forEach(function (line) {
- const parts = line.split(": ");
- const headerName = parts.shift();
- if (!headerName) {
- logger.warn("skipping invalid header");
- return;
- }
- const value = parts.join(": ");
- headerMap.set(headerName, value);
- });
- const resp: HttpResponse = {
- requestUrl: url,
- status: myRequest.status,
- headers: headerMap,
- json: makeJson,
- text: async () => myRequest.responseText,
- };
- resolve(resp);
- }
- });
- });
- }
-
- get(url: string, opt?: HttpRequestOptions): Promise<HttpResponse> {
- return this.req("get", url, undefined, opt);
- }
-
- postJson(
- url: string,
- body: unknown,
- opt?: HttpRequestOptions,
- ): Promise<HttpResponse> {
- return this.req("post", url, JSON.stringify(body), opt);
- }
-
- stop(): void {
- // Nothing to do
- }
-}
-
-type TalerErrorResponse = {
- code: number;
-} & unknown;
-
-type ResponseOrError<T> =
- | { isError: false; response: T }
- | { isError: true; talerErrorResponse: TalerErrorResponse };
-
-export async function readSuccessResponseJsonOrErrorCode<T>(
- httpResponse: HttpResponse,
- codec: Codec<T>,
-): Promise<ResponseOrError<T>> {
- if (!(httpResponse.status >= 200 && httpResponse.status < 300)) {
- const errJson = await httpResponse.json();
- const talerErrorCode = errJson.code;
- if (typeof talerErrorCode !== "number") {
- throw new OperationFailedError(
- makeErrorDetails(
- TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE,
- "Error response did not contain error code",
- {
- requestUrl: httpResponse.requestUrl,
- },
- ),
- );
- }
- return {
- isError: true,
- talerErrorResponse: errJson,
- };
- }
- const respJson = await httpResponse.json();
- let parsedResponse: T;
- try {
- parsedResponse = codec.decode(respJson);
- } catch (e) {
- throw OperationFailedError.fromCode(
- TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE,
- "Response invalid",
- {
- requestUrl: httpResponse.requestUrl,
- httpStatusCode: httpResponse.status,
- validationError: e.toString(),
- },
- );
- }
- return {
- isError: false,
- response: parsedResponse,
- };
-}
-
-export function throwUnexpectedRequestError(
- httpResponse: HttpResponse,
- talerErrorResponse: TalerErrorResponse,
-): never {
- throw new OperationFailedError(
- makeErrorDetails(
- TalerErrorCode.WALLET_UNEXPECTED_REQUEST_ERROR,
- "Unexpected error code in response",
- {
- requestUrl: httpResponse.requestUrl,
- httpStatusCode: httpResponse.status,
- errorResponse: talerErrorResponse,
- },
- ),
- );
-}
-
-export async function readSuccessResponseJsonOrThrow<T>(
- httpResponse: HttpResponse,
- codec: Codec<T>,
-): Promise<T> {
- const r = await readSuccessResponseJsonOrErrorCode(httpResponse, codec);
- if (!r.isError) {
- return r.response;
- }
- throwUnexpectedRequestError(httpResponse, r.talerErrorResponse);
-}
-
-
-export async function readSuccessResponseTextOrErrorCode<T>(
- httpResponse: HttpResponse,
-): Promise<ResponseOrError<string>> {
- if (!(httpResponse.status >= 200 && httpResponse.status < 300)) {
- const errJson = await httpResponse.json();
- const talerErrorCode = errJson.code;
- if (typeof talerErrorCode !== "number") {
- throw new OperationFailedError(
- makeErrorDetails(
- TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE,
- "Error response did not contain error code",
- {
- requestUrl: httpResponse.requestUrl,
- },
- ),
- );
- }
- return {
- isError: true,
- talerErrorResponse: errJson,
- };
- }
- const respJson = await httpResponse.text();
- return {
- isError: false,
- response: respJson,
- };
-}
-
-export async function checkSuccessResponseOrThrow(
- httpResponse: HttpResponse,
-): Promise<void> {
- if (!(httpResponse.status >= 200 && httpResponse.status < 300)) {
- const errJson = await httpResponse.json();
- const talerErrorCode = errJson.code;
- if (typeof talerErrorCode !== "number") {
- throw new OperationFailedError(
- makeErrorDetails(
- TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE,
- "Error response did not contain error code",
- {
- requestUrl: httpResponse.requestUrl,
- },
- ),
- );
- }
- throwUnexpectedRequestError(httpResponse, errJson);
- }
-}
-
-export async function readSuccessResponseTextOrThrow<T>(
- httpResponse: HttpResponse,
-): Promise<string> {
- const r = await readSuccessResponseTextOrErrorCode(httpResponse);
- if (!r.isError) {
- return r.response;
- }
- throwUnexpectedRequestError(httpResponse, r.talerErrorResponse);
-}
diff --git a/src/util/libtoolVersion-test.ts b/src/util/libtoolVersion-test.ts
deleted file mode 100644
index e58e94759..000000000
--- a/src/util/libtoolVersion-test.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- This file is part of TALER
- (C) 2017 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-import * as LibtoolVersion from "./libtoolVersion";
-
-import test from "ava";
-
-test("version comparison", (t) => {
- t.deepEqual(LibtoolVersion.compare("0:0:0", "0:0:0"), {
- compatible: true,
- currentCmp: 0,
- });
- t.deepEqual(LibtoolVersion.compare("0:0:0", ""), undefined);
- t.deepEqual(LibtoolVersion.compare("foo", "0:0:0"), undefined);
- t.deepEqual(LibtoolVersion.compare("0:0:0", "1:0:1"), {
- compatible: true,
- currentCmp: -1,
- });
- t.deepEqual(LibtoolVersion.compare("0:0:0", "1:5:1"), {
- compatible: true,
- currentCmp: -1,
- });
- t.deepEqual(LibtoolVersion.compare("0:0:0", "1:5:0"), {
- compatible: false,
- currentCmp: -1,
- });
- t.deepEqual(LibtoolVersion.compare("1:0:0", "0:5:0"), {
- compatible: false,
- currentCmp: 1,
- });
- t.deepEqual(LibtoolVersion.compare("1:0:1", "1:5:1"), {
- compatible: true,
- currentCmp: 0,
- });
-});
diff --git a/src/util/libtoolVersion.ts b/src/util/libtoolVersion.ts
deleted file mode 100644
index 5e9d0b74e..000000000
--- a/src/util/libtoolVersion.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- This file is part of TALER
- (C) 2017 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Semantic versioning, but libtool-style.
- * See https://www.gnu.org/software/libtool/manual/html_node/Libtool-versioning.html
- */
-
-/**
- * Result of comparing two libtool versions.
- */
-export interface VersionMatchResult {
- /**
- * Is the first version compatible with the second?
- */
- compatible: boolean;
- /**
- * Is the first version older (-1), newser (+1) or
- * identical (0)?
- */
- currentCmp: number;
-}
-
-interface Version {
- current: number;
- revision: number;
- age: number;
-}
-
-/**
- * Compare two libtool-style version strings.
- */
-export function compare(
- me: string,
- other: string,
-): VersionMatchResult | undefined {
- const meVer = parseVersion(me);
- const otherVer = parseVersion(other);
-
- if (!(meVer && otherVer)) {
- return undefined;
- }
-
- const compatible =
- meVer.current - meVer.age <= otherVer.current &&
- meVer.current >= otherVer.current - otherVer.age;
-
- const currentCmp = Math.sign(meVer.current - otherVer.current);
-
- return { compatible, currentCmp };
-}
-
-function parseVersion(v: string): Version | undefined {
- const [currentStr, revisionStr, ageStr, ...rest] = v.split(":");
- if (rest.length !== 0) {
- return undefined;
- }
- const current = Number.parseInt(currentStr);
- const revision = Number.parseInt(revisionStr);
- const age = Number.parseInt(ageStr);
-
- if (Number.isNaN(current)) {
- return undefined;
- }
-
- if (Number.isNaN(revision)) {
- return undefined;
- }
-
- if (Number.isNaN(age)) {
- return undefined;
- }
-
- return { current, revision, age };
-}
diff --git a/src/util/logging.ts b/src/util/logging.ts
deleted file mode 100644
index 83e8d2192..000000000
--- a/src/util/logging.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- This file is part of TALER
- (C) 2019 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Imports.
- */
-import { isNode } from "../webex/compat";
-
-function writeNodeLog(
- message: string,
- tag: string,
- level: string,
- args: any[],
-): void {
- process.stderr.write(`${new Date().toISOString()} ${tag} ${level} `);
- process.stderr.write(message);
- if (args.length != 0) {
- process.stderr.write(" ");
- process.stderr.write(JSON.stringify(args, undefined, 2));
- }
- process.stderr.write("\n");
-}
-
-/**
- * Logger that writes to stderr when running under node,
- * and uses the corresponding console.* method to log in the browser.
- */
-export class Logger {
- constructor(private tag: string) {}
-
- info(message: string, ...args: any[]): void {
- if (isNode()) {
- writeNodeLog(message, this.tag, "INFO", args);
- } else {
- console.info(
- `${new Date().toISOString()} ${this.tag} INFO ` + message,
- ...args,
- );
- }
- }
-
- warn(message: string, ...args: any[]): void {
- if (isNode()) {
- writeNodeLog(message, this.tag, "WARN", args);
- } else {
- console.warn(
- `${new Date().toISOString()} ${this.tag} INFO ` + message,
- ...args,
- );
- }
- }
-
- error(message: string, ...args: any[]): void {
- if (isNode()) {
- writeNodeLog(message, this.tag, "ERROR", args);
- } else {
- console.info(
- `${new Date().toISOString()} ${this.tag} ERROR ` + message,
- ...args,
- );
- }
- }
-
- trace(message: any, ...args: any[]): void {
- if (isNode()) {
- writeNodeLog(message, this.tag, "TRACE", args);
- } else {
- console.info(
- `${new Date().toISOString()} ${this.tag} TRACE ` + message,
- ...args,
- );
- }
- }
-}
diff --git a/src/util/payto-test.ts b/src/util/payto-test.ts
deleted file mode 100644
index 01280b650..000000000
--- a/src/util/payto-test.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- 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 test from "ava";
-
-import { parsePaytoUri } from "./payto";
-
-test("basic payto parsing", (t) => {
- const r1 = parsePaytoUri("https://example.com/");
- t.is(r1, undefined);
-
- const r2 = parsePaytoUri("payto:blabla");
- t.is(r2, undefined);
-
- const r3 = parsePaytoUri("payto://x-taler-bank/123");
- t.is(r3?.targetType, "x-taler-bank");
- t.is(r3?.targetPath, "123");
-});
diff --git a/src/util/payto.ts b/src/util/payto.ts
deleted file mode 100644
index 835214b86..000000000
--- a/src/util/payto.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- 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/>
- */
-
-interface PaytoUri {
- targetType: string;
- targetPath: string;
- params: { [name: string]: string };
-}
-
-const paytoPfx = "payto://";
-
-/**
- * Add query parameters to a payto URI
- */
-export function addPaytoQueryParams(
- s: string,
- params: { [name: string]: string },
-): string {
- const [acct, search] = s.slice(paytoPfx.length).split("?");
- const searchParams = new URLSearchParams(search || "");
- for (const k of Object.keys(params)) {
- searchParams.set(k, params[k]);
- }
- return paytoPfx + acct + "?" + searchParams.toString();
-}
-
-export function parsePaytoUri(s: string): PaytoUri | undefined {
- if (!s.startsWith(paytoPfx)) {
- return undefined;
- }
-
- const [acct, search] = s.slice(paytoPfx.length).split("?");
-
- const firstSlashPos = acct.indexOf("/");
-
- if (firstSlashPos === -1) {
- return undefined;
- }
-
- const targetType = acct.slice(0, firstSlashPos);
- const targetPath = acct.slice(firstSlashPos + 1);
-
- const params: { [k: string]: string } = {};
-
- const searchParams = new URLSearchParams(search || "");
-
- searchParams.forEach((v, k) => {
- params[v] = k;
- });
-
- return {
- targetPath,
- targetType,
- params,
- };
-}
diff --git a/src/util/promiseUtils.ts b/src/util/promiseUtils.ts
deleted file mode 100644
index d409686d9..000000000
--- a/src/util/promiseUtils.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2019 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-export interface OpenedPromise<T> {
- promise: Promise<T>;
- resolve: (val: T) => void;
- reject: (err: any) => void;
-}
-
-/**
- * Get an unresolved promise together with its extracted resolve / reject
- * function.
- */
-export function openPromise<T>(): OpenedPromise<T> {
- let resolve: ((x?: any) => void) | null = null;
- let reject: ((reason?: any) => void) | null = null;
- const promise = new Promise<T>((res, rej) => {
- resolve = res;
- reject = rej;
- });
- if (!(resolve && reject)) {
- // Never happens, unless JS implementation is broken
- throw Error();
- }
- return { resolve, reject, promise };
-}
-
-export class AsyncCondition {
- private _waitPromise: Promise<void>;
- private _resolveWaitPromise: (val: void) => void;
- constructor() {
- const op = openPromise<void>();
- this._waitPromise = op.promise;
- this._resolveWaitPromise = op.resolve;
- }
-
- wait(): Promise<void> {
- return this._waitPromise;
- }
-
- trigger(): void {
- this._resolveWaitPromise();
- const op = openPromise<void>();
- this._waitPromise = op.promise;
- this._resolveWaitPromise = op.resolve;
- }
-}
diff --git a/src/util/query.ts b/src/util/query.ts
deleted file mode 100644
index be319049b..000000000
--- a/src/util/query.ts
+++ /dev/null
@@ -1,575 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Database query abstractions.
- * @module Query
- * @author Florian Dold
- */
-
-/**
- * Imports.
- */
-import { openPromise } from "./promiseUtils";
-
-/**
- * Exception that should be thrown by client code to abort a transaction.
- */
-export const TransactionAbort = Symbol("transaction_abort");
-
-/**
- * Definition of an object store.
- */
-export class Store<T> {
- constructor(
- public name: string,
- public storeParams?: IDBObjectStoreParameters,
- public validator?: (v: T) => T,
- ) {}
-}
-
-/**
- * Options for an index.
- */
-export interface IndexOptions {
- /**
- * If true and the path resolves to an array, create an index entry for
- * each member of the array (instead of one index entry containing the full array).
- *
- * Defaults to false.
- */
- multiEntry?: boolean;
-}
-
-function requestToPromise(req: IDBRequest): Promise<any> {
- const stack = Error("Failed request was started here.");
- return new Promise((resolve, reject) => {
- req.onsuccess = () => {
- resolve(req.result);
- };
- req.onerror = () => {
- console.log("error in DB request", req.error);
- reject(req.error);
- console.log("Request failed:", stack);
- };
- });
-}
-
-function transactionToPromise(tx: IDBTransaction): Promise<void> {
- const stack = Error("Failed transaction was started here.");
- return new Promise((resolve, reject) => {
- tx.onabort = () => {
- reject(TransactionAbort);
- };
- tx.oncomplete = () => {
- resolve();
- };
- tx.onerror = () => {
- console.error("Transaction failed:", stack);
- reject(tx.error);
- };
- });
-}
-
-function applyMutation<T>(
- req: IDBRequest,
- f: (x: T) => T | undefined,
-): Promise<void> {
- return new Promise((resolve, reject) => {
- req.onsuccess = () => {
- const cursor = req.result;
- if (cursor) {
- const val = cursor.value;
- const modVal = f(val);
- if (modVal !== undefined && modVal !== null) {
- const req2: IDBRequest = cursor.update(modVal);
- req2.onerror = () => {
- reject(req2.error);
- };
- req2.onsuccess = () => {
- cursor.continue();
- };
- } else {
- cursor.continue();
- }
- } else {
- resolve();
- }
- };
- req.onerror = () => {
- reject(req.error);
- };
- });
-}
-
-type CursorResult<T> = CursorEmptyResult<T> | CursorValueResult<T>;
-
-interface CursorEmptyResult<T> {
- hasValue: false;
-}
-
-interface CursorValueResult<T> {
- hasValue: true;
- value: T;
-}
-
-class ResultStream<T> {
- private currentPromise: Promise<void>;
- private gotCursorEnd = false;
- private awaitingResult = false;
-
- constructor(private req: IDBRequest) {
- this.awaitingResult = true;
- let p = openPromise<void>();
- this.currentPromise = p.promise;
- req.onsuccess = () => {
- if (!this.awaitingResult) {
- throw Error("BUG: invariant violated");
- }
- const cursor = req.result;
- if (cursor) {
- this.awaitingResult = false;
- p.resolve();
- p = openPromise<void>();
- this.currentPromise = p.promise;
- } else {
- this.gotCursorEnd = true;
- p.resolve();
- }
- };
- req.onerror = () => {
- p.reject(req.error);
- };
- }
-
- async toArray(): Promise<T[]> {
- const arr: T[] = [];
- while (true) {
- const x = await this.next();
- if (x.hasValue) {
- arr.push(x.value);
- } else {
- break;
- }
- }
- return arr;
- }
-
- async map<R>(f: (x: T) => R): Promise<R[]> {
- const arr: R[] = [];
- while (true) {
- const x = await this.next();
- if (x.hasValue) {
- arr.push(f(x.value));
- } else {
- break;
- }
- }
- return arr;
- }
-
- async forEachAsync(f: (x: T) => Promise<void>): Promise<void> {
- while (true) {
- const x = await this.next();
- if (x.hasValue) {
- await f(x.value);
- } else {
- break;
- }
- }
- }
-
- async forEach(f: (x: T) => void): Promise<void> {
- while (true) {
- const x = await this.next();
- if (x.hasValue) {
- f(x.value);
- } else {
- break;
- }
- }
- }
-
- async filter(f: (x: T) => boolean): Promise<T[]> {
- const arr: T[] = [];
- while (true) {
- const x = await this.next();
- if (x.hasValue) {
- if (f(x.value)) {
- arr.push(x.value);
- }
- } else {
- break;
- }
- }
- return arr;
- }
-
- async next(): Promise<CursorResult<T>> {
- if (this.gotCursorEnd) {
- return { hasValue: false };
- }
- if (!this.awaitingResult) {
- const cursor: IDBCursor | undefined = this.req.result;
- if (!cursor) {
- throw Error("assertion failed");
- }
- this.awaitingResult = true;
- cursor.continue();
- }
- await this.currentPromise;
- if (this.gotCursorEnd) {
- return { hasValue: false };
- }
- const cursor = this.req.result;
- if (!cursor) {
- throw Error("assertion failed");
- }
- return { hasValue: true, value: cursor.value };
- }
-}
-
-export class TransactionHandle {
- constructor(private tx: IDBTransaction) {}
-
- put<T>(store: Store<T>, value: T, key?: any): Promise<any> {
- const req = this.tx.objectStore(store.name).put(value, key);
- return requestToPromise(req);
- }
-
- add<T>(store: Store<T>, value: T, key?: any): Promise<any> {
- const req = this.tx.objectStore(store.name).add(value, key);
- return requestToPromise(req);
- }
-
- get<T>(store: Store<T>, key: any): Promise<T | undefined> {
- const req = this.tx.objectStore(store.name).get(key);
- return requestToPromise(req);
- }
-
- getIndexed<S extends IDBValidKey, T>(
- index: Index<S, T>,
- key: any,
- ): Promise<T | undefined> {
- const req = this.tx
- .objectStore(index.storeName)
- .index(index.indexName)
- .get(key);
- return requestToPromise(req);
- }
-
- iter<T>(store: Store<T>, key?: any): ResultStream<T> {
- const req = this.tx.objectStore(store.name).openCursor(key);
- return new ResultStream<T>(req);
- }
-
- iterIndexed<S extends IDBValidKey, T>(
- index: Index<S, T>,
- key?: any,
- ): ResultStream<T> {
- const req = this.tx
- .objectStore(index.storeName)
- .index(index.indexName)
- .openCursor(key);
- return new ResultStream<T>(req);
- }
-
- delete<T>(store: Store<T>, key: any): Promise<void> {
- const req = this.tx.objectStore(store.name).delete(key);
- return requestToPromise(req);
- }
-
- mutate<T>(
- store: Store<T>,
- key: any,
- f: (x: T) => T | undefined,
- ): Promise<void> {
- const req = this.tx.objectStore(store.name).openCursor(key);
- return applyMutation(req, f);
- }
-}
-
-function runWithTransaction<T>(
- db: IDBDatabase,
- stores: Store<any>[],
- f: (t: TransactionHandle) => Promise<T>,
- mode: "readonly" | "readwrite",
-): Promise<T> {
- const stack = Error("Failed transaction was started here.");
- return new Promise((resolve, reject) => {
- const storeName = stores.map((x) => x.name);
- const tx = db.transaction(storeName, mode);
- let funResult: any = undefined;
- let gotFunResult = false;
- tx.oncomplete = () => {
- // This is a fatal error: The transaction completed *before*
- // the transaction function returned. Likely, the transaction
- // function waited on a promise that is *not* resolved in the
- // microtask queue, thus triggering the auto-commit behavior.
- // Unfortunately, the auto-commit behavior of IDB can't be switched
- // of. There are some proposals to add this functionality in the future.
- if (!gotFunResult) {
- const msg =
- "BUG: transaction closed before transaction function returned";
- console.error(msg);
- reject(Error(msg));
- }
- resolve(funResult);
- };
- tx.onerror = () => {
- console.error("error in transaction");
- console.error(stack);
- };
- tx.onabort = () => {
- if (tx.error) {
- console.error("Transaction aborted with error:", tx.error);
- } else {
- console.log("Trasaction aborted (no error)");
- }
- reject(TransactionAbort);
- };
- const th = new TransactionHandle(tx);
- const resP = Promise.resolve().then(() => f(th));
- resP
- .then((result) => {
- gotFunResult = true;
- funResult = result;
- })
- .catch((e) => {
- if (e == TransactionAbort) {
- console.info("aborting transaction");
- } else {
- console.error("Transaction failed:", e);
- console.error(stack);
- tx.abort();
- }
- })
- .catch((e) => {
- console.error("fatal: aborting transaction failed", e);
- });
- });
-}
-
-/**
- * Definition of an index.
- */
-export class Index<S extends IDBValidKey, T> {
- /**
- * Name of the store that this index is associated with.
- */
- storeName: string;
-
- /**
- * Options to use for the index.
- */
- options: IndexOptions;
-
- constructor(
- s: Store<T>,
- public indexName: string,
- public keyPath: string | string[],
- options?: IndexOptions,
- ) {
- const defaultOptions = {
- multiEntry: false,
- };
- this.options = { ...defaultOptions, ...(options || {}) };
- this.storeName = s.name;
- }
-
- /**
- * We want to have the key type parameter in use somewhere,
- * because otherwise the compiler complains. In iterIndex the
- * key type is pretty useful.
- */
- protected _dummyKey: S | undefined;
-}
-
-/**
- * Return a promise that resolves
- * to the taler wallet db.
- */
-export function openDatabase(
- idbFactory: IDBFactory,
- databaseName: string,
- databaseVersion: number,
- onVersionChange: () => void,
- onUpgradeNeeded: (
- db: IDBDatabase,
- oldVersion: number,
- newVersion: number,
- ) => void,
-): Promise<IDBDatabase> {
- return new Promise<IDBDatabase>((resolve, reject) => {
- const req = idbFactory.open(databaseName, databaseVersion);
- req.onerror = (e) => {
- console.log("taler database error", e);
- reject(new Error("database error"));
- };
- req.onsuccess = (e) => {
- req.result.onversionchange = (evt: IDBVersionChangeEvent) => {
- console.log(
- `handling live db version change from ${evt.oldVersion} to ${evt.newVersion}`,
- );
- req.result.close();
- onVersionChange();
- };
- resolve(req.result);
- };
- req.onupgradeneeded = (e) => {
- const db = req.result;
- const newVersion = e.newVersion;
- if (!newVersion) {
- throw Error("upgrade needed, but new version unknown");
- }
- onUpgradeNeeded(db, e.oldVersion, newVersion);
- };
- });
-}
-
-export class Database {
- constructor(private db: IDBDatabase) {}
-
- static deleteDatabase(idbFactory: IDBFactory, dbName: string): void {
- idbFactory.deleteDatabase(dbName);
- }
-
- async exportDatabase(): Promise<any> {
- const db = this.db;
- const dump = {
- name: db.name,
- stores: {} as { [s: string]: any },
- version: db.version,
- };
-
- return new Promise((resolve, reject) => {
- const tx = db.transaction(Array.from(db.objectStoreNames));
- tx.addEventListener("complete", () => {
- resolve(dump);
- });
- // tslint:disable-next-line:prefer-for-of
- for (let i = 0; i < db.objectStoreNames.length; i++) {
- const name = db.objectStoreNames[i];
- const storeDump = {} as { [s: string]: any };
- dump.stores[name] = storeDump;
- tx.objectStore(name)
- .openCursor()
- .addEventListener("success", (e: Event) => {
- const cursor = (e.target as any).result;
- if (cursor) {
- storeDump[cursor.key] = cursor.value;
- cursor.continue();
- }
- });
- }
- });
- }
-
- importDatabase(dump: any): Promise<void> {
- const db = this.db;
- console.log("importing db", dump);
- return new Promise<void>((resolve, reject) => {
- const tx = db.transaction(Array.from(db.objectStoreNames), "readwrite");
- if (dump.stores) {
- for (const storeName in dump.stores) {
- const objects = [];
- const dumpStore = dump.stores[storeName];
- for (const key in dumpStore) {
- objects.push(dumpStore[key]);
- }
- console.log(`importing ${objects.length} records into ${storeName}`);
- const store = tx.objectStore(storeName);
- for (const obj of objects) {
- store.put(obj);
- }
- }
- }
- tx.addEventListener("complete", () => {
- resolve();
- });
- });
- }
-
- async get<T>(store: Store<T>, key: any): Promise<T | undefined> {
- const tx = this.db.transaction([store.name], "readonly");
- const req = tx.objectStore(store.name).get(key);
- const v = await requestToPromise(req);
- await transactionToPromise(tx);
- return v;
- }
-
- async getIndexed<S extends IDBValidKey, T>(
- index: Index<S, T>,
- key: any,
- ): Promise<T | undefined> {
- const tx = this.db.transaction([index.storeName], "readonly");
- const req = tx.objectStore(index.storeName).index(index.indexName).get(key);
- const v = await requestToPromise(req);
- await transactionToPromise(tx);
- return v;
- }
-
- async put<T>(store: Store<T>, value: T, key?: any): Promise<any> {
- const tx = this.db.transaction([store.name], "readwrite");
- const req = tx.objectStore(store.name).put(value, key);
- const v = await requestToPromise(req);
- await transactionToPromise(tx);
- return v;
- }
-
- async mutate<T>(
- store: Store<T>,
- key: any,
- f: (x: T) => T | undefined,
- ): Promise<void> {
- const tx = this.db.transaction([store.name], "readwrite");
- const req = tx.objectStore(store.name).openCursor(key);
- await applyMutation(req, f);
- await transactionToPromise(tx);
- }
-
- iter<T>(store: Store<T>): ResultStream<T> {
- const tx = this.db.transaction([store.name], "readonly");
- const req = tx.objectStore(store.name).openCursor();
- return new ResultStream<T>(req);
- }
-
- iterIndex<S extends IDBValidKey, T>(
- index: Index<S, T>,
- query?: any,
- ): ResultStream<T> {
- const tx = this.db.transaction([index.storeName], "readonly");
- const req = tx
- .objectStore(index.storeName)
- .index(index.indexName)
- .openCursor(query);
- return new ResultStream<T>(req);
- }
-
- async runWithReadTransaction<T>(
- stores: Store<any>[],
- f: (t: TransactionHandle) => Promise<T>,
- ): Promise<T> {
- return runWithTransaction<T>(this.db, stores, f, "readonly");
- }
-
- async runWithWriteTransaction<T>(
- stores: Store<any>[],
- f: (t: TransactionHandle) => Promise<T>,
- ): Promise<T> {
- return runWithTransaction<T>(this.db, stores, f, "readwrite");
- }
-}
diff --git a/src/util/reserveHistoryUtil-test.ts b/src/util/reserveHistoryUtil-test.ts
deleted file mode 100644
index 79022de77..000000000
--- a/src/util/reserveHistoryUtil-test.ts
+++ /dev/null
@@ -1,285 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2020 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 test from "ava";
-import {
- reconcileReserveHistory,
- summarizeReserveHistory,
-} from "./reserveHistoryUtil";
-import {
- WalletReserveHistoryItem,
- WalletReserveHistoryItemType,
-} from "../types/dbTypes";
-import {
- ReserveTransaction,
- ReserveTransactionType,
-} from "../types/ReserveTransaction";
-import { Amounts } from "./amounts";
-
-test("basics", (t) => {
- const r = reconcileReserveHistory([], []);
- t.deepEqual(r.updatedLocalHistory, []);
-});
-
-test("unmatched credit", (t) => {
- const localHistory: WalletReserveHistoryItem[] = [];
- const remoteHistory: ReserveTransaction[] = [
- {
- type: ReserveTransactionType.Credit,
- amount: "TESTKUDOS:100",
- sender_account_url: "payto://void/",
- timestamp: { t_ms: 42 },
- wire_reference: "ABC01",
- },
- ];
- const r = reconcileReserveHistory(localHistory, remoteHistory);
- const s = summarizeReserveHistory(r.updatedLocalHistory, "TESTKUDOS");
- t.deepEqual(r.updatedLocalHistory.length, 1);
- t.deepEqual(Amounts.stringify(s.computedReserveBalance), "TESTKUDOS:100");
- t.deepEqual(Amounts.stringify(s.awaitedReserveAmount), "TESTKUDOS:0");
- t.deepEqual(Amounts.stringify(s.unclaimedReserveAmount), "TESTKUDOS:100");
-});
-
-test("unmatched credit #2", (t) => {
- const localHistory: WalletReserveHistoryItem[] = [];
- const remoteHistory: ReserveTransaction[] = [
- {
- type: ReserveTransactionType.Credit,
- amount: "TESTKUDOS:100",
- sender_account_url: "payto://void/",
- timestamp: { t_ms: 42 },
- wire_reference: "ABC01",
- },
- {
- type: ReserveTransactionType.Credit,
- amount: "TESTKUDOS:50",
- sender_account_url: "payto://void/",
- timestamp: { t_ms: 42 },
- wire_reference: "ABC02",
- },
- ];
- const r = reconcileReserveHistory(localHistory, remoteHistory);
- const s = summarizeReserveHistory(r.updatedLocalHistory, "TESTKUDOS");
- t.deepEqual(r.updatedLocalHistory.length, 2);
- t.deepEqual(Amounts.stringify(s.computedReserveBalance), "TESTKUDOS:150");
- t.deepEqual(Amounts.stringify(s.awaitedReserveAmount), "TESTKUDOS:0");
- t.deepEqual(Amounts.stringify(s.unclaimedReserveAmount), "TESTKUDOS:150");
-});
-
-test("matched credit", (t) => {
- const localHistory: WalletReserveHistoryItem[] = [
- {
- type: WalletReserveHistoryItemType.Credit,
- expectedAmount: Amounts.parseOrThrow("TESTKUDOS:100"),
- matchedExchangeTransaction: {
- type: ReserveTransactionType.Credit,
- amount: "TESTKUDOS:100",
- sender_account_url: "payto://void/",
- timestamp: { t_ms: 42 },
- wire_reference: "ABC01",
- },
- },
- ];
- const remoteHistory: ReserveTransaction[] = [
- {
- type: ReserveTransactionType.Credit,
- amount: "TESTKUDOS:100",
- sender_account_url: "payto://void/",
- timestamp: { t_ms: 42 },
- wire_reference: "ABC01",
- },
- {
- type: ReserveTransactionType.Credit,
- amount: "TESTKUDOS:50",
- sender_account_url: "payto://void/",
- timestamp: { t_ms: 42 },
- wire_reference: "ABC02",
- },
- ];
- const r = reconcileReserveHistory(localHistory, remoteHistory);
- const s = summarizeReserveHistory(r.updatedLocalHistory, "TESTKUDOS");
- t.deepEqual(r.updatedLocalHistory.length, 2);
- t.deepEqual(Amounts.stringify(s.computedReserveBalance), "TESTKUDOS:150");
- t.deepEqual(Amounts.stringify(s.awaitedReserveAmount), "TESTKUDOS:0");
- t.deepEqual(Amounts.stringify(s.unclaimedReserveAmount), "TESTKUDOS:150");
-});
-
-test("fulfilling credit", (t) => {
- const localHistory: WalletReserveHistoryItem[] = [
- {
- type: WalletReserveHistoryItemType.Credit,
- expectedAmount: Amounts.parseOrThrow("TESTKUDOS:100"),
- },
- ];
- const remoteHistory: ReserveTransaction[] = [
- {
- type: ReserveTransactionType.Credit,
- amount: "TESTKUDOS:100",
- sender_account_url: "payto://void/",
- timestamp: { t_ms: 42 },
- wire_reference: "ABC01",
- },
- {
- type: ReserveTransactionType.Credit,
- amount: "TESTKUDOS:50",
- sender_account_url: "payto://void/",
- timestamp: { t_ms: 42 },
- wire_reference: "ABC02",
- },
- ];
- const r = reconcileReserveHistory(localHistory, remoteHistory);
- const s = summarizeReserveHistory(r.updatedLocalHistory, "TESTKUDOS");
- t.deepEqual(r.updatedLocalHistory.length, 2);
- t.deepEqual(Amounts.stringify(s.computedReserveBalance), "TESTKUDOS:150");
-});
-
-test("unfulfilled credit", (t) => {
- const localHistory: WalletReserveHistoryItem[] = [
- {
- type: WalletReserveHistoryItemType.Credit,
- expectedAmount: Amounts.parseOrThrow("TESTKUDOS:100"),
- },
- ];
- const remoteHistory: ReserveTransaction[] = [
- {
- type: ReserveTransactionType.Credit,
- amount: "TESTKUDOS:100",
- sender_account_url: "payto://void/",
- timestamp: { t_ms: 42 },
- wire_reference: "ABC01",
- },
- {
- type: ReserveTransactionType.Credit,
- amount: "TESTKUDOS:50",
- sender_account_url: "payto://void/",
- timestamp: { t_ms: 42 },
- wire_reference: "ABC02",
- },
- ];
- const r = reconcileReserveHistory(localHistory, remoteHistory);
- const s = summarizeReserveHistory(r.updatedLocalHistory, "TESTKUDOS");
- t.deepEqual(r.updatedLocalHistory.length, 2);
- t.deepEqual(Amounts.stringify(s.computedReserveBalance), "TESTKUDOS:150");
-});
-
-test("awaited credit", (t) => {
- const localHistory: WalletReserveHistoryItem[] = [
- {
- type: WalletReserveHistoryItemType.Credit,
- expectedAmount: Amounts.parseOrThrow("TESTKUDOS:50"),
- },
- {
- type: WalletReserveHistoryItemType.Credit,
- expectedAmount: Amounts.parseOrThrow("TESTKUDOS:100"),
- },
- ];
- const remoteHistory: ReserveTransaction[] = [
- {
- type: ReserveTransactionType.Credit,
- amount: "TESTKUDOS:100",
- sender_account_url: "payto://void/",
- timestamp: { t_ms: 42 },
- wire_reference: "ABC01",
- },
- ];
- const r = reconcileReserveHistory(localHistory, remoteHistory);
- const s = summarizeReserveHistory(r.updatedLocalHistory, "TESTKUDOS");
- t.deepEqual(r.updatedLocalHistory.length, 2);
- t.deepEqual(Amounts.stringify(s.computedReserveBalance), "TESTKUDOS:100");
- t.deepEqual(Amounts.stringify(s.awaitedReserveAmount), "TESTKUDOS:50");
- t.deepEqual(Amounts.stringify(s.unclaimedReserveAmount), "TESTKUDOS:100");
-});
-
-test("withdrawal new match", (t) => {
- const localHistory: WalletReserveHistoryItem[] = [
- {
- type: WalletReserveHistoryItemType.Credit,
- expectedAmount: Amounts.parseOrThrow("TESTKUDOS:100"),
- matchedExchangeTransaction: {
- type: ReserveTransactionType.Credit,
- amount: "TESTKUDOS:100",
- sender_account_url: "payto://void/",
- timestamp: { t_ms: 42 },
- wire_reference: "ABC01",
- },
- },
- {
- type: WalletReserveHistoryItemType.Withdraw,
- expectedAmount: Amounts.parseOrThrow("TESTKUDOS:5"),
- },
- ];
- const remoteHistory: ReserveTransaction[] = [
- {
- type: ReserveTransactionType.Credit,
- amount: "TESTKUDOS:100",
- sender_account_url: "payto://void/",
- timestamp: { t_ms: 42 },
- wire_reference: "ABC01",
- },
- {
- type: ReserveTransactionType.Withdraw,
- amount: "TESTKUDOS:5",
- h_coin_envelope: "foobar",
- h_denom_pub: "foobar",
- reserve_sig: "foobar",
- withdraw_fee: "TESTKUDOS:0.1",
- },
- ];
- const r = reconcileReserveHistory(localHistory, remoteHistory);
- const s = summarizeReserveHistory(r.updatedLocalHistory, "TESTKUDOS");
- t.deepEqual(r.updatedLocalHistory.length, 2);
- t.deepEqual(Amounts.stringify(s.computedReserveBalance), "TESTKUDOS:95");
- t.deepEqual(Amounts.stringify(s.awaitedReserveAmount), "TESTKUDOS:0");
- t.deepEqual(Amounts.stringify(s.unclaimedReserveAmount), "TESTKUDOS:95");
-});
-
-test("claimed but now arrived", (t) => {
- const localHistory: WalletReserveHistoryItem[] = [
- {
- type: WalletReserveHistoryItemType.Credit,
- expectedAmount: Amounts.parseOrThrow("TESTKUDOS:100"),
- matchedExchangeTransaction: {
- type: ReserveTransactionType.Credit,
- amount: "TESTKUDOS:100",
- sender_account_url: "payto://void/",
- timestamp: { t_ms: 42 },
- wire_reference: "ABC01",
- },
- },
- {
- type: WalletReserveHistoryItemType.Withdraw,
- expectedAmount: Amounts.parseOrThrow("TESTKUDOS:5"),
- },
- ];
- const remoteHistory: ReserveTransaction[] = [
- {
- type: ReserveTransactionType.Credit,
- amount: "TESTKUDOS:100",
- sender_account_url: "payto://void/",
- timestamp: { t_ms: 42 },
- wire_reference: "ABC01",
- },
- ];
- const r = reconcileReserveHistory(localHistory, remoteHistory);
- const s = summarizeReserveHistory(r.updatedLocalHistory, "TESTKUDOS");
- t.deepEqual(r.updatedLocalHistory.length, 2);
- t.deepEqual(Amounts.stringify(s.computedReserveBalance), "TESTKUDOS:100");
- t.deepEqual(Amounts.stringify(s.awaitedReserveAmount), "TESTKUDOS:0");
- t.deepEqual(Amounts.stringify(s.unclaimedReserveAmount), "TESTKUDOS:95");
-});
diff --git a/src/util/reserveHistoryUtil.ts b/src/util/reserveHistoryUtil.ts
deleted file mode 100644
index 855b71a3d..000000000
--- a/src/util/reserveHistoryUtil.ts
+++ /dev/null
@@ -1,360 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2020 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 {
- WalletReserveHistoryItem,
- WalletReserveHistoryItemType,
-} from "../types/dbTypes";
-import {
- ReserveTransaction,
- ReserveTransactionType,
-} from "../types/ReserveTransaction";
-import * as Amounts from "../util/amounts";
-import { timestampCmp } from "./time";
-import { deepCopy } from "./helpers";
-import { AmountJson } from "../util/amounts";
-
-/**
- * Helpers for dealing with reserve histories.
- *
- * @author Florian Dold <dold@taler.net>
- */
-
-export interface ReserveReconciliationResult {
- /**
- * The wallet's local history reconciled with the exchange's reserve history.
- */
- updatedLocalHistory: WalletReserveHistoryItem[];
-
- /**
- * History items that were newly created, subset of the
- * updatedLocalHistory items.
- */
- newAddedItems: WalletReserveHistoryItem[];
-
- /**
- * History items that were newly matched, subset of the
- * updatedLocalHistory items.
- */
- newMatchedItems: WalletReserveHistoryItem[];
-}
-
-/**
- * Various totals computed from the wallet's view
- * on the reserve history.
- */
-export interface ReserveHistorySummary {
- /**
- * Balance computed by the wallet, should match the balance
- * computed by the reserve.
- */
- computedReserveBalance: Amounts.AmountJson;
-
- /**
- * Reserve balance that is still available for withdrawal.
- */
- unclaimedReserveAmount: Amounts.AmountJson;
-
- /**
- * Amount that we're still expecting to come into the reserve.
- */
- awaitedReserveAmount: Amounts.AmountJson;
-
- /**
- * Amount withdrawn from the reserve so far. Only counts
- * finished withdrawals, not withdrawals in progress.
- */
- withdrawnAmount: Amounts.AmountJson;
-}
-
-/**
- * Check if two reserve history items (exchange's version) match.
- */
-function isRemoteHistoryMatch(
- t1: ReserveTransaction,
- t2: ReserveTransaction,
-): boolean {
- switch (t1.type) {
- case ReserveTransactionType.Closing: {
- return t1.type === t2.type && t1.wtid == t2.wtid;
- }
- case ReserveTransactionType.Credit: {
- return t1.type === t2.type && t1.wire_reference === t2.wire_reference;
- }
- case ReserveTransactionType.Recoup: {
- return (
- t1.type === t2.type &&
- t1.coin_pub === t2.coin_pub &&
- timestampCmp(t1.timestamp, t2.timestamp) === 0
- );
- }
- case ReserveTransactionType.Withdraw: {
- return t1.type === t2.type && t1.h_coin_envelope === t2.h_coin_envelope;
- }
- }
-}
-
-/**
- * Check a local reserve history item and a remote history item are a match.
- */
-export function isLocalRemoteHistoryMatch(
- t1: WalletReserveHistoryItem,
- t2: ReserveTransaction,
-): boolean {
- switch (t1.type) {
- case WalletReserveHistoryItemType.Credit: {
- return (
- t2.type === ReserveTransactionType.Credit &&
- !!t1.expectedAmount &&
- Amounts.cmp(t1.expectedAmount, Amounts.parseOrThrow(t2.amount)) === 0
- );
- }
- case WalletReserveHistoryItemType.Withdraw:
- return (
- t2.type === ReserveTransactionType.Withdraw &&
- !!t1.expectedAmount &&
- Amounts.cmp(t1.expectedAmount, Amounts.parseOrThrow(t2.amount)) === 0
- );
- case WalletReserveHistoryItemType.Recoup: {
- return (
- t2.type === ReserveTransactionType.Recoup &&
- !!t1.expectedAmount &&
- Amounts.cmp(t1.expectedAmount, Amounts.parseOrThrow(t2.amount)) === 0
- );
- }
- }
- return false;
-}
-
-/**
- * Compute totals for the wallet's view of the reserve history.
- */
-export function summarizeReserveHistory(
- localHistory: WalletReserveHistoryItem[],
- currency: string,
-): ReserveHistorySummary {
- const posAmounts: AmountJson[] = [];
- const negAmounts: AmountJson[] = [];
- const expectedPosAmounts: AmountJson[] = [];
- const expectedNegAmounts: AmountJson[] = [];
- const withdrawnAmounts: AmountJson[] = [];
-
- for (const item of localHistory) {
- switch (item.type) {
- case WalletReserveHistoryItemType.Credit:
- if (item.matchedExchangeTransaction) {
- posAmounts.push(
- Amounts.parseOrThrow(item.matchedExchangeTransaction.amount),
- );
- } else if (item.expectedAmount) {
- expectedPosAmounts.push(item.expectedAmount);
- }
- break;
- case WalletReserveHistoryItemType.Recoup:
- if (item.matchedExchangeTransaction) {
- if (item.matchedExchangeTransaction) {
- posAmounts.push(
- Amounts.parseOrThrow(item.matchedExchangeTransaction.amount),
- );
- } else if (item.expectedAmount) {
- expectedPosAmounts.push(item.expectedAmount);
- } else {
- throw Error("invariant failed");
- }
- }
- break;
- case WalletReserveHistoryItemType.Closing:
- if (item.matchedExchangeTransaction) {
- negAmounts.push(
- Amounts.parseOrThrow(item.matchedExchangeTransaction.amount),
- );
- } else {
- throw Error("invariant failed");
- }
- break;
- case WalletReserveHistoryItemType.Withdraw:
- if (item.matchedExchangeTransaction) {
- negAmounts.push(
- Amounts.parseOrThrow(item.matchedExchangeTransaction.amount),
- );
- withdrawnAmounts.push(
- Amounts.parseOrThrow(item.matchedExchangeTransaction.amount),
- );
- } else if (item.expectedAmount) {
- expectedNegAmounts.push(item.expectedAmount);
- } else {
- throw Error("invariant failed");
- }
- break;
- }
- }
-
- const z = Amounts.getZero(currency);
-
- const computedBalance = Amounts.sub(
- Amounts.add(z, ...posAmounts).amount,
- ...negAmounts,
- ).amount;
-
- const unclaimedReserveAmount = Amounts.sub(
- Amounts.add(z, ...posAmounts).amount,
- ...negAmounts,
- ...expectedNegAmounts,
- ).amount;
-
- const awaitedReserveAmount = Amounts.sub(
- Amounts.add(z, ...expectedPosAmounts).amount,
- ...expectedNegAmounts,
- ).amount;
-
- const withdrawnAmount = Amounts.add(z, ...withdrawnAmounts).amount;
-
- return {
- computedReserveBalance: computedBalance,
- unclaimedReserveAmount: unclaimedReserveAmount,
- awaitedReserveAmount: awaitedReserveAmount,
- withdrawnAmount,
- };
-}
-
-/**
- * Reconcile the wallet's local model of the reserve history
- * with the reserve history of the exchange.
- */
-export function reconcileReserveHistory(
- localHistory: WalletReserveHistoryItem[],
- remoteHistory: ReserveTransaction[],
-): ReserveReconciliationResult {
- const updatedLocalHistory: WalletReserveHistoryItem[] = deepCopy(
- localHistory,
- );
- const newMatchedItems: WalletReserveHistoryItem[] = [];
- const newAddedItems: WalletReserveHistoryItem[] = [];
-
- const remoteMatched = remoteHistory.map(() => false);
- const localMatched = localHistory.map(() => false);
-
- // Take care of deposits
-
- // First, see which pairs are already a definite match.
- for (let remoteIndex = 0; remoteIndex < remoteHistory.length; remoteIndex++) {
- const rhi = remoteHistory[remoteIndex];
- for (let localIndex = 0; localIndex < localHistory.length; localIndex++) {
- if (localMatched[localIndex]) {
- continue;
- }
- const lhi = localHistory[localIndex];
- if (!lhi.matchedExchangeTransaction) {
- continue;
- }
- if (isRemoteHistoryMatch(rhi, lhi.matchedExchangeTransaction)) {
- localMatched[localIndex] = true;
- remoteMatched[remoteIndex] = true;
- break;
- }
- }
- }
-
- // Check that all previously matched items are still matched
- for (let localIndex = 0; localIndex < localHistory.length; localIndex++) {
- if (localMatched[localIndex]) {
- continue;
- }
- const lhi = localHistory[localIndex];
- if (lhi.matchedExchangeTransaction) {
- // Don't use for further matching
- localMatched[localIndex] = true;
- // FIXME: emit some error here!
- throw Error("previously matched reserve history item now unmatched");
- }
- }
-
- // Next, find out if there are any exact new matches between local and remote
- // history items
- for (let localIndex = 0; localIndex < localHistory.length; localIndex++) {
- if (localMatched[localIndex]) {
- continue;
- }
- const lhi = localHistory[localIndex];
- for (
- let remoteIndex = 0;
- remoteIndex < remoteHistory.length;
- remoteIndex++
- ) {
- const rhi = remoteHistory[remoteIndex];
- if (remoteMatched[remoteIndex]) {
- continue;
- }
- if (isLocalRemoteHistoryMatch(lhi, rhi)) {
- localMatched[localIndex] = true;
- remoteMatched[remoteIndex] = true;
- updatedLocalHistory[localIndex].matchedExchangeTransaction = rhi as any;
- newMatchedItems.push(lhi);
- break;
- }
- }
- }
-
- // Finally we add new history items
- for (let remoteIndex = 0; remoteIndex < remoteHistory.length; remoteIndex++) {
- if (remoteMatched[remoteIndex]) {
- continue;
- }
- const rhi = remoteHistory[remoteIndex];
- let newItem: WalletReserveHistoryItem;
- switch (rhi.type) {
- case ReserveTransactionType.Closing: {
- newItem = {
- type: WalletReserveHistoryItemType.Closing,
- matchedExchangeTransaction: rhi,
- };
- break;
- }
- case ReserveTransactionType.Credit: {
- newItem = {
- type: WalletReserveHistoryItemType.Credit,
- matchedExchangeTransaction: rhi,
- };
- break;
- }
- case ReserveTransactionType.Recoup: {
- newItem = {
- type: WalletReserveHistoryItemType.Recoup,
- matchedExchangeTransaction: rhi,
- };
- break;
- }
- case ReserveTransactionType.Withdraw: {
- newItem = {
- type: WalletReserveHistoryItemType.Withdraw,
- matchedExchangeTransaction: rhi,
- };
- break;
- }
- }
- updatedLocalHistory.push(newItem);
- newAddedItems.push(newItem);
- }
-
- return {
- updatedLocalHistory,
- newAddedItems,
- newMatchedItems,
- };
-}
diff --git a/src/util/talerconfig.ts b/src/util/talerconfig.ts
deleted file mode 100644
index ec08c352f..000000000
--- a/src/util/talerconfig.ts
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2020 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/>
- */
-
-/**
- * Utilities to handle Taler-style configuration files.
- *
- * @author Florian Dold <dold@taler.net>
- */
-
-/**
- * Imports
- */
-import { AmountJson } from "./amounts";
-import * as Amounts from "./amounts";
-
-export class ConfigError extends Error {
- constructor(message: string) {
- super();
- Object.setPrototypeOf(this, ConfigError.prototype);
- this.name = "ConfigError";
- this.message = message;
- }
-}
-
-type OptionMap = { [optionName: string]: string };
-type SectionMap = { [sectionName: string]: OptionMap };
-
-export class ConfigValue<T> {
- constructor(
- private sectionName: string,
- private optionName: string,
- private val: string | undefined,
- private converter: (x: string) => T,
- ) {}
-
- required(): T {
- if (!this.val) {
- throw new ConfigError(
- `required option [${this.sectionName}]/${this.optionName} not found`,
- );
- }
- return this.converter(this.val);
- }
-}
-
-export class Configuration {
- private sectionMap: SectionMap = {};
-
- loadFromString(s: string): void {
- const reComment = /^\s*#.*$/;
- const reSection = /^\s*\[\s*([^\]]*)\s*\]\s*$/;
- const reParam = /^\s*([^=]+?)\s*=\s*(.*?)\s*$/;
- const reEmptyLine = /^\s*$/;
-
- let currentSection: string | undefined = undefined;
-
- const lines = s.split("\n");
- for (const line of lines) {
- console.log("parsing line", JSON.stringify(line));
- if (reEmptyLine.test(line)) {
- continue;
- }
- if (reComment.test(line)) {
- continue;
- }
- const secMatch = line.match(reSection);
- if (secMatch) {
- currentSection = secMatch[1];
- console.log("setting section to", currentSection);
- continue;
- }
- if (currentSection === undefined) {
- throw Error("invalid configuration, expected section header");
- }
- const paramMatch = line.match(reParam);
- if (paramMatch) {
- const optName = paramMatch[1];
- let val = paramMatch[2];
- if (val.startsWith('"') && val.endsWith('"')) {
- val = val.slice(1, val.length - 1);
- }
- const sec = this.sectionMap[currentSection] ?? {};
- this.sectionMap[currentSection] = Object.assign(sec, {
- [optName]: val,
- });
- continue;
- }
- throw Error(
- "invalid configuration, expected section header or option assignment",
- );
- }
-
- console.log("parsed config", JSON.stringify(this.sectionMap, undefined, 2));
- }
-
- getString(section: string, option: string): ConfigValue<string> {
- const val = (this.sectionMap[section] ?? {})[option];
- return new ConfigValue(section, option, val, (x) => x);
- }
-
- getAmount(section: string, option: string): ConfigValue<AmountJson> {
- const val = (this.sectionMap[section] ?? {})[option];
- return new ConfigValue(section, option, val, (x) =>
- Amounts.parseOrThrow(x),
- );
- }
-}
diff --git a/src/util/taleruri-test.ts b/src/util/taleruri-test.ts
deleted file mode 100644
index 44edbe1c1..000000000
--- a/src/util/taleruri-test.ts
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- 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 test from "ava";
-import {
- parsePayUri,
- parseWithdrawUri,
- parseRefundUri,
- parseTipUri,
-} from "./taleruri";
-
-test("taler pay url parsing: wrong scheme", (t) => {
- const url1 = "talerfoo://";
- const r1 = parsePayUri(url1);
- t.is(r1, undefined);
-
- const url2 = "taler://refund/a/b/c/d/e/f";
- const r2 = parsePayUri(url2);
- t.is(r2, undefined);
-});
-
-test("taler pay url parsing: defaults", (t) => {
- const url1 = "taler://pay/example.com/myorder/";
- const r1 = parsePayUri(url1);
- if (!r1) {
- t.fail();
- return;
- }
- t.is(r1.merchantBaseUrl, "https://example.com/");
- t.is(r1.sessionId, "");
-
- const url2 = "taler://pay/example.com/myorder/mysession";
- const r2 = parsePayUri(url2);
- if (!r2) {
- t.fail();
- return;
- }
- t.is(r2.merchantBaseUrl, "https://example.com/");
- t.is(r2.sessionId, "mysession");
-});
-
-test("taler pay url parsing: instance", (t) => {
- const url1 = "taler://pay/example.com/instances/myinst/myorder/";
- const r1 = parsePayUri(url1);
- if (!r1) {
- t.fail();
- return;
- }
- t.is(r1.merchantBaseUrl, "https://example.com/instances/myinst/");
- t.is(r1.orderId, "myorder");
-});
-
-test("taler pay url parsing (claim token)", (t) => {
- const url1 = "taler://pay/example.com/instances/myinst/myorder/?c=ASDF";
- const r1 = parsePayUri(url1);
- if (!r1) {
- t.fail();
- return;
- }
- t.is(r1.merchantBaseUrl, "https://example.com/instances/myinst/");
- t.is(r1.orderId, "myorder");
- t.is(r1.claimToken, "ASDF");
-});
-
-test("taler refund uri parsing: non-https #1", (t) => {
- const url1 = "taler+http://refund/example.com/myorder";
- const r1 = parseRefundUri(url1);
- if (!r1) {
- t.fail();
- return;
- }
- t.is(r1.merchantBaseUrl, "http://example.com/");
- t.is(r1.orderId, "myorder");
-});
-
-test("taler pay uri parsing: non-https", (t) => {
- const url1 = "taler+http://pay/example.com/myorder/";
- const r1 = parsePayUri(url1);
- if (!r1) {
- t.fail();
- return;
- }
- t.is(r1.merchantBaseUrl, "http://example.com/");
- t.is(r1.orderId, "myorder");
-});
-
-test("taler pay uri parsing: missing session component", (t) => {
- const url1 = "taler+http://pay/example.com/myorder";
- const r1 = parsePayUri(url1);
- if (r1) {
- t.fail();
- return;
- }
- t.pass();
-});
-
-test("taler withdraw uri parsing", (t) => {
- const url1 = "taler://withdraw/bank.example.com/12345";
- const r1 = parseWithdrawUri(url1);
- if (!r1) {
- t.fail();
- return;
- }
- t.is(r1.withdrawalOperationId, "12345");
- t.is(r1.bankIntegrationApiBaseUrl, "https://bank.example.com/");
-});
-
-test("taler withdraw uri parsing (http)", (t) => {
- const url1 = "taler+http://withdraw/bank.example.com/12345";
- const r1 = parseWithdrawUri(url1);
- if (!r1) {
- t.fail();
- return;
- }
- t.is(r1.withdrawalOperationId, "12345");
- t.is(r1.bankIntegrationApiBaseUrl, "http://bank.example.com/");
-});
-
-test("taler refund uri parsing", (t) => {
- const url1 = "taler://refund/merchant.example.com/1234";
- const r1 = parseRefundUri(url1);
- if (!r1) {
- t.fail();
- return;
- }
- t.is(r1.merchantBaseUrl, "https://merchant.example.com/");
- t.is(r1.orderId, "1234");
-});
-
-test("taler refund uri parsing with instance", (t) => {
- const url1 = "taler://refund/merchant.example.com/instances/myinst/1234";
- const r1 = parseRefundUri(url1);
- if (!r1) {
- t.fail();
- return;
- }
- t.is(r1.orderId, "1234");
- t.is(
- r1.merchantBaseUrl,
- "https://merchant.example.com/instances/myinst/",
- );
-});
-
-test("taler tip pickup uri", (t) => {
- const url1 = "taler://tip/merchant.example.com/tipid";
- const r1 = parseTipUri(url1);
- if (!r1) {
- t.fail();
- return;
- }
- t.is(r1.merchantBaseUrl, "https://merchant.example.com/");
-});
-
-test("taler tip pickup uri with instance", (t) => {
- const url1 = "taler://tip/merchant.example.com/instances/tipm/tipid";
- const r1 = parseTipUri(url1);
- if (!r1) {
- t.fail();
- return;
- }
- t.is(
- r1.merchantBaseUrl,
- "https://merchant.example.com/instances/tipm/",
- );
- t.is(r1.merchantTipId, "tipid");
-});
-
-test("taler tip pickup uri with instance and prefix", (t) => {
- const url1 = "taler://tip/merchant.example.com/my/pfx/tipm/tipid";
- const r1 = parseTipUri(url1);
- if (!r1) {
- t.fail();
- return;
- }
- t.is(
- r1.merchantBaseUrl,
- "https://merchant.example.com/my/pfx/tipm/",
- );
- t.is(r1.merchantTipId, "tipid");
-});
diff --git a/src/util/taleruri.ts b/src/util/taleruri.ts
deleted file mode 100644
index c26c4a5db..000000000
--- a/src/util/taleruri.ts
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2019-2020 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/>
- */
-
-export interface PayUriResult {
- merchantBaseUrl: string;
- orderId: string;
- sessionId: string;
- claimToken: string | undefined;
-}
-
-export interface WithdrawUriResult {
- bankIntegrationApiBaseUrl: string;
- withdrawalOperationId: string;
-}
-
-export interface RefundUriResult {
- merchantBaseUrl: string;
- orderId: string;
-}
-
-export interface TipUriResult {
- merchantTipId: string;
- merchantBaseUrl: string;
-}
-
-/**
- * Parse a taler[+http]://withdraw URI.
- * Return undefined if not passed a valid URI.
- */
-export function parseWithdrawUri(s: string): WithdrawUriResult | undefined {
- const pi = parseProtoInfo(s, "withdraw");
- if (!pi) {
- return undefined;
- }
- const parts = pi.rest.split("/");
-
- if (parts.length < 2) {
- return undefined;
- }
-
- const host = parts[0].toLowerCase();
- const pathSegments = parts.slice(1, parts.length - 1);
- const withdrawId = parts[parts.length - 1];
- const p = [host, ...pathSegments].join("/");
-
- return {
- bankIntegrationApiBaseUrl: `${pi.innerProto}://${p}/`,
- withdrawalOperationId: withdrawId,
- };
-}
-
-export const enum TalerUriType {
- TalerPay = "taler-pay",
- TalerWithdraw = "taler-withdraw",
- TalerTip = "taler-tip",
- TalerRefund = "taler-refund",
- TalerNotifyReserve = "taler-notify-reserve",
- Unknown = "unknown",
-}
-
-/**
- * Classify a taler:// URI.
- */
-export function classifyTalerUri(s: string): TalerUriType {
- const sl = s.toLowerCase();
- if (sl.startsWith("taler://pay/")) {
- return TalerUriType.TalerPay;
- }
- if (sl.startsWith("taler+http://pay/")) {
- return TalerUriType.TalerPay;
- }
- if (sl.startsWith("taler://tip/")) {
- return TalerUriType.TalerTip;
- }
- if (sl.startsWith("taler+http://tip/")) {
- return TalerUriType.TalerTip;
- }
- if (sl.startsWith("taler://refund/")) {
- return TalerUriType.TalerRefund;
- }
- if (sl.startsWith("taler+http://refund/")) {
- return TalerUriType.TalerRefund;
- }
- if (sl.startsWith("taler://withdraw/")) {
- return TalerUriType.TalerWithdraw;
- }
- if (sl.startsWith("taler://notify-reserve/")) {
- return TalerUriType.TalerNotifyReserve;
- }
- return TalerUriType.Unknown;
-}
-
-interface TalerUriProtoInfo {
- innerProto: "http" | "https";
- rest: string;
-}
-
-
-function parseProtoInfo(s: string, action: string): TalerUriProtoInfo | undefined {
- const pfxPlain = `taler://${action}/`;
- const pfxHttp = `taler+http://${action}/`;
- if (s.toLowerCase().startsWith(pfxPlain)) {
- return {
- innerProto: "https",
- rest: s.substring(pfxPlain.length),
- }
- } else if (s.toLowerCase().startsWith(pfxHttp)) {
- return {
- innerProto: "http",
- rest: s.substring(pfxHttp.length),
- }
- } else {
- return undefined;
- }
-}
-
-/**
- * Parse a taler[+http]://pay URI.
- * Return undefined if not passed a valid URI.
- */
-export function parsePayUri(s: string): PayUriResult | undefined {
- const pi = parseProtoInfo(s, "pay");
- if (!pi) {
- return undefined;
- }
- const c = pi?.rest.split("?");
- const q = new URLSearchParams(c[1] ?? "");
- const claimToken = q.get("c") ?? undefined;
- const parts = c[0].split("/");
- if (parts.length < 3) {
- return undefined;
- }
- const host = parts[0].toLowerCase();
- const sessionId = parts[parts.length - 1];
- const orderId = parts[parts.length - 2];
- const pathSegments = parts.slice(1, parts.length - 2);
- const p = [host, ...pathSegments].join("/");
- const merchantBaseUrl = `${pi.innerProto}://${p}/`;
-
- return {
- merchantBaseUrl,
- orderId,
- sessionId: sessionId,
- claimToken,
- };
-}
-
-/**
- * Parse a taler[+http]://tip URI.
- * Return undefined if not passed a valid URI.
- */
-export function parseTipUri(s: string): TipUriResult | undefined {
- const pi = parseProtoInfo(s, "tip");
- if (!pi) {
- return undefined;
- }
- const c = pi?.rest.split("?");
- const parts = c[0].split("/");
- if (parts.length < 2) {
- return undefined;
- }
- const host = parts[0].toLowerCase();
- const tipId = parts[parts.length - 1];
- const pathSegments = parts.slice(1, parts.length - 1);
- const p = [host, ...pathSegments].join("/");
- const merchantBaseUrl = `${pi.innerProto}://${p}/`;
-
- return {
- merchantBaseUrl,
- merchantTipId: tipId,
- };
-}
-
-/**
- * Parse a taler[+http]://refund URI.
- * Return undefined if not passed a valid URI.
- */
-export function parseRefundUri(s: string): RefundUriResult | undefined {
- const pi = parseProtoInfo(s, "refund");
- if (!pi) {
- return undefined;
- }
- const c = pi?.rest.split("?");
- const parts = c[0].split("/");
- if (parts.length < 2) {
- return undefined;
- }
- const host = parts[0].toLowerCase();
- const orderId = parts[parts.length - 1];
- const pathSegments = parts.slice(1, parts.length - 1);
- const p = [host, ...pathSegments].join("/");
- const merchantBaseUrl = `${pi.innerProto}://${p}/`;
-
- return {
- merchantBaseUrl,
- orderId,
- };
-}
diff --git a/src/util/time.ts b/src/util/time.ts
deleted file mode 100644
index 5c2f49d12..000000000
--- a/src/util/time.ts
+++ /dev/null
@@ -1,198 +0,0 @@
-import { Codec, renderContext, Context } from "./codec";
-
-/*
- This file is part of GNU Taler
- (C) 2017-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/>
- */
-
-/**
- * Helpers for relative and absolute time.
- */
-
-export class Timestamp {
- /**
- * Timestamp in milliseconds.
- */
- readonly t_ms: number | "never";
-}
-
-export interface Duration {
- /**
- * Duration in milliseconds.
- */
- readonly d_ms: number | "forever";
-}
-
-let timeshift = 0;
-
-export function setDangerousTimetravel(dt: number): void {
- timeshift = dt;
-}
-
-export function getTimestampNow(): Timestamp {
- return {
- t_ms: new Date().getTime() + timeshift,
- };
-}
-
-export function getDurationRemaining(
- deadline: Timestamp,
- now = getTimestampNow(),
-): Duration {
- if (deadline.t_ms === "never") {
- return { d_ms: "forever" };
- }
- if (now.t_ms === "never") {
- throw Error("invalid argument for 'now'");
- }
- if (deadline.t_ms < now.t_ms) {
- return { d_ms: 0 };
- }
- return { d_ms: deadline.t_ms - now.t_ms };
-}
-
-export function timestampMin(t1: Timestamp, t2: Timestamp): Timestamp {
- if (t1.t_ms === "never") {
- return { t_ms: t2.t_ms };
- }
- if (t2.t_ms === "never") {
- return { t_ms: t2.t_ms };
- }
- return { t_ms: Math.min(t1.t_ms, t2.t_ms) };
-}
-
-/**
- * Truncate a timestamp so that that it represents a multiple
- * of seconds. The timestamp is always rounded down.
- */
-export function timestampTruncateToSecond(t1: Timestamp): Timestamp {
- if (t1.t_ms === "never") {
- return { t_ms: "never" };
- }
- return {
- t_ms: Math.floor(t1.t_ms / 1000) * 1000,
- };
-}
-
-export function durationMin(d1: Duration, d2: Duration): Duration {
- if (d1.d_ms === "forever") {
- return { d_ms: d2.d_ms };
- }
- if (d2.d_ms === "forever") {
- return { d_ms: d2.d_ms };
- }
- return { d_ms: Math.min(d1.d_ms, d2.d_ms) };
-}
-
-export function timestampCmp(t1: Timestamp, t2: Timestamp): number {
- if (t1.t_ms === "never") {
- if (t2.t_ms === "never") {
- return 0;
- }
- return 1;
- }
- if (t2.t_ms === "never") {
- return -1;
- }
- if (t1.t_ms == t2.t_ms) {
- return 0;
- }
- if (t1.t_ms > t2.t_ms) {
- return 1;
- }
- return -1;
-}
-
-export function timestampAddDuration(t1: Timestamp, d: Duration): Timestamp {
- if (t1.t_ms === "never" || d.d_ms === "forever") {
- return { t_ms: "never" };
- }
- return { t_ms: t1.t_ms + d.d_ms };
-}
-
-export function timestampSubtractDuraction(
- t1: Timestamp,
- d: Duration,
-): Timestamp {
- if (t1.t_ms === "never") {
- return { t_ms: "never" };
- }
- if (d.d_ms === "forever") {
- return { t_ms: 0 };
- }
- return { t_ms: Math.max(0, t1.t_ms - d.d_ms) };
-}
-
-export function stringifyTimestamp(t: Timestamp): string {
- if (t.t_ms === "never") {
- return "never";
- }
- return new Date(t.t_ms).toISOString();
-}
-
-export function timestampDifference(t1: Timestamp, t2: Timestamp): Duration {
- if (t1.t_ms === "never") {
- return { d_ms: "forever" };
- }
- if (t2.t_ms === "never") {
- return { d_ms: "forever" };
- }
- return { d_ms: Math.abs(t1.t_ms - t2.t_ms) };
-}
-
-export function timestampIsBetween(
- t: Timestamp,
- start: Timestamp,
- end: Timestamp,
-): boolean {
- if (timestampCmp(t, start) < 0) {
- return false;
- }
- if (timestampCmp(t, end) > 0) {
- return false;
- }
- return true;
-}
-
-export const codecForTimestamp: Codec<Timestamp> = {
- decode(x: any, c?: Context): Timestamp {
- const t_ms = x.t_ms;
- if (typeof t_ms === "string") {
- if (t_ms === "never") {
- return { t_ms: "never" };
- }
- throw Error(`expected timestamp at ${renderContext(c)}`);
- }
- if (typeof t_ms === "number") {
- return { t_ms };
- }
- throw Error(`expected timestamp at ${renderContext(c)}`);
- },
-};
-
-export const codecForDuration: Codec<Duration> = {
- decode(x: any, c?: Context): Duration {
- const d_ms = x.d_ms;
- if (typeof d_ms === "string") {
- if (d_ms === "forever") {
- return { d_ms: "forever" };
- }
- throw Error(`expected duration at ${renderContext(c)}`);
- }
- if (typeof d_ms === "number") {
- return { d_ms };
- }
- throw Error(`expected duration at ${renderContext(c)}`);
- },
-};
diff --git a/src/util/timer.ts b/src/util/timer.ts
deleted file mode 100644
index 5f37a6f4d..000000000
--- a/src/util/timer.ts
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2017-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/>
- */
-
-/**
- * Cross-platform timers.
- *
- * NodeJS and the browser use slightly different timer API,
- * this abstracts over these differences.
- */
-
-/**
- * Imports.
- */
-import { Duration } from "./time";
-import { Logger } from "./logging";
-
-const logger = new Logger("timer.ts");
-
-/**
- * Cancelable timer.
- */
-export interface TimerHandle {
- clear(): void;
-}
-
-class IntervalHandle {
- constructor(public h: any) {}
-
- clear(): void {
- clearInterval(this.h);
- }
-}
-
-class TimeoutHandle {
- constructor(public h: any) {}
-
- clear(): void {
- clearTimeout(this.h);
- }
-}
-
-/**
- * Get a performance counter in milliseconds.
- */
-export const performanceNow: () => number = (() => {
- if (typeof process !== "undefined" && process.hrtime) {
- return () => {
- const t = process.hrtime();
- return t[0] * 1e9 + t[1];
- };
- } else if (typeof performance !== "undefined") {
- return () => performance.now();
- } else {
- return () => 0;
- }
-})();
-
-/**
- * Call a function every time the delay given in milliseconds passes.
- */
-export function every(delayMs: number, callback: () => void): TimerHandle {
- return new IntervalHandle(setInterval(callback, delayMs));
-}
-
-/**
- * Call a function after the delay given in milliseconds passes.
- */
-export function after(delayMs: number, callback: () => void): TimerHandle {
- return new TimeoutHandle(setTimeout(callback, delayMs));
-}
-
-const nullTimerHandle = {
- clear() {
- // do nothing
- return;
- },
-};
-
-/**
- * Group of timers that can be destroyed at once.
- */
-export class TimerGroup {
- private stopped = false;
-
- private timerMap: { [index: number]: TimerHandle } = {};
-
- private idGen = 1;
-
- stopCurrentAndFutureTimers(): void {
- this.stopped = true;
- for (const x in this.timerMap) {
- if (!this.timerMap.hasOwnProperty(x)) {
- continue;
- }
- this.timerMap[x].clear();
- delete this.timerMap[x];
- }
- }
-
- resolveAfter(delayMs: Duration): Promise<void> {
- return new Promise<void>((resolve, reject) => {
- if (delayMs.d_ms !== "forever") {
- this.after(delayMs.d_ms, () => {
- resolve();
- });
- }
- });
- }
-
- after(delayMs: number, callback: () => void): TimerHandle {
- if (this.stopped) {
- logger.warn("dropping timer since timer group is stopped");
- return nullTimerHandle;
- }
- const h = after(delayMs, callback);
- const myId = this.idGen++;
- this.timerMap[myId] = h;
-
- const tm = this.timerMap;
-
- return {
- clear() {
- h.clear();
- delete tm[myId];
- },
- };
- }
-
- every(delayMs: number, callback: () => void): TimerHandle {
- if (this.stopped) {
- logger.warn("dropping timer since timer group is stopped");
- return nullTimerHandle;
- }
- const h = every(delayMs, callback);
- const myId = this.idGen++;
- this.timerMap[myId] = h;
-
- const tm = this.timerMap;
-
- return {
- clear() {
- h.clear();
- delete tm[myId];
- },
- };
- }
-}
diff --git a/src/util/wire.ts b/src/util/wire.ts
deleted file mode 100644
index 21ad600fc..000000000
--- a/src/util/wire.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- This file is part of TALER
- (C) 2017 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Display and manipulate wire information.
- *
- * Right now, all types are hard-coded. In the future, there might be plugins / configurable
- * methods or support for the "payto://" URI scheme.
- */
-
-/**
- * Imports.
- */
-import * as i18n from "../webex/i18n";
-
-/**
- * Short summary of the wire information.
- *
- * Might abbreviate and return the same summary for different
- * wire details.
- */
-export function summarizeWire(w: any): string {
- if (!w.type) {
- return i18n.str`Invalid Wire`;
- }
- switch (w.type.toLowerCase()) {
- case "test":
- if (!w.account_number && w.account_number !== 0) {
- return i18n.str`Invalid Test Wire Detail`;
- }
- if (!w.bank_uri) {
- return i18n.str`Invalid Test Wire Detail`;
- }
- return i18n.str`Test Wire Acct #${w.account_number} on ${w.bank_uri}`;
- default:
- return i18n.str`Unknown Wire Detail`;
- }
-}
diff --git a/src/wallet-test.ts b/src/wallet-test.ts
deleted file mode 100644
index 4b06accf2..000000000
--- a/src/wallet-test.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- This file is part of TALER
- (C) 2017 Inria and GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-import test from "ava";
-
-import { AmountJson } from "./util/amounts";
-import * as Amounts from "./util/amounts";
-import { selectPayCoins, AvailableCoinInfo } from "./operations/pay";
-
-function a(x: string): AmountJson {
- const amt = Amounts.parse(x);
- if (!amt) {
- throw Error("invalid amount");
- }
- return amt;
-}
-
-function fakeAci(current: string, feeDeposit: string): AvailableCoinInfo {
- return {
- availableAmount: a(current),
- coinPub: "foobar",
- denomPub: "foobar",
- feeDeposit: a(feeDeposit),
- };
-}
-
-test("coin selection 1", (t) => {
- const acis: AvailableCoinInfo[] = [
- fakeAci("EUR:1.0", "EUR:0.1"),
- fakeAci("EUR:1.0", "EUR:0.0"),
- ];
-
- const res = selectPayCoins(acis, a("EUR:2.0"), a("EUR:0"), a("EUR:0.1"));
- if (!res) {
- t.fail();
- return;
- }
- t.true(res.coinPubs.length === 2);
- t.pass();
-});
-
-test("coin selection 2", (t) => {
- const acis: AvailableCoinInfo[] = [
- fakeAci("EUR:1.0", "EUR:0.5"),
- fakeAci("EUR:1.0", "EUR:0.0"),
- // Merchant covers the fee, this one shouldn't be used
- fakeAci("EUR:1.0", "EUR:0.0"),
- ];
- const res = selectPayCoins(acis, a("EUR:2.0"), a("EUR:0"), a("EUR:0.5"));
- if (!res) {
- t.fail();
- return;
- }
- t.true(res.coinPubs.length === 2);
- t.pass();
-});
-
-test("coin selection 3", (t) => {
- const acis: AvailableCoinInfo[] = [
- fakeAci("EUR:1.0", "EUR:0.5"),
- fakeAci("EUR:1.0", "EUR:0.5"),
- // this coin should be selected instead of previous one with fee
- fakeAci("EUR:1.0", "EUR:0.0"),
- ];
- const res = selectPayCoins(acis, a("EUR:2.0"), a("EUR:0"), a("EUR:0.5"));
- if (!res) {
- t.fail();
- return;
- }
- t.true(res.coinPubs.length === 2);
- t.pass();
-});
-
-test("coin selection 4", (t) => {
- const acis: AvailableCoinInfo[] = [
- fakeAci("EUR:1.0", "EUR:0.5"),
- fakeAci("EUR:1.0", "EUR:0.5"),
- fakeAci("EUR:1.0", "EUR:0.5"),
- ];
- const res = selectPayCoins(acis, a("EUR:2.0"), a("EUR:0"), a("EUR:0.5"));
- if (!res) {
- t.fail();
- return;
- }
- t.true(res.coinPubs.length === 3);
- t.pass();
-});
-
-test("coin selection 5", (t) => {
- const acis: AvailableCoinInfo[] = [
- fakeAci("EUR:1.0", "EUR:0.5"),
- fakeAci("EUR:1.0", "EUR:0.5"),
- fakeAci("EUR:1.0", "EUR:0.5"),
- ];
- const res = selectPayCoins(acis, a("EUR:4.0"), a("EUR:0"), a("EUR:0.2"));
- t.true(!res);
- t.pass();
-});
-
-test("coin selection 6", (t) => {
- const acis: AvailableCoinInfo[] = [
- fakeAci("EUR:1.0", "EUR:0.5"),
- fakeAci("EUR:1.0", "EUR:0.5"),
- ];
- const res = selectPayCoins(acis, a("EUR:2.0"), a("EUR:0"), a("EUR:0.2"));
- t.true(!res);
- t.pass();
-});
diff --git a/src/wallet.ts b/src/wallet.ts
deleted file mode 100644
index 4d22bd591..000000000
--- a/src/wallet.ts
+++ /dev/null
@@ -1,881 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2015-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/>
- */
-
-/**
- * High-level wallet operations that should be indepentent from the underlying
- * browser extension interface.
- */
-
-/**
- * Imports.
- */
-import { CryptoWorkerFactory } from "./crypto/workers/cryptoApi";
-import { HttpRequestLibrary } from "./util/http";
-import { Database } from "./util/query";
-
-import { Amounts, AmountJson } from "./util/amounts";
-
-import {
- getExchangeWithdrawalInfo,
- getWithdrawalDetailsForUri,
-} from "./operations/withdraw";
-
-import {
- preparePayForUri,
- refuseProposal,
- confirmPay,
- processDownloadProposal,
- processPurchasePay,
-} from "./operations/pay";
-
-import {
- CoinRecord,
- CurrencyRecord,
- DenominationRecord,
- ExchangeRecord,
- PurchaseRecord,
- ReserveRecord,
- Stores,
- ReserveRecordStatus,
- CoinSourceType,
- RefundState,
-} from "./types/dbTypes";
-import { CoinDumpJson, WithdrawUriInfoResponse } from "./types/talerTypes";
-import {
- BenchmarkResult,
- ConfirmPayResult,
- ReturnCoinsRequest,
- SenderWireInfos,
- TipStatus,
- PreparePayResult,
- AcceptWithdrawalResponse,
- PurchaseDetails,
- RefreshReason,
- ExchangeListItem,
- ExchangesListRespose,
- ManualWithdrawalDetails,
- GetExchangeTosResult,
- AcceptManualWithdrawalResult,
- BalancesResponse,
-} from "./types/walletTypes";
-import { Logger } from "./util/logging";
-
-import { assertUnreachable } from "./util/assertUnreachable";
-
-import {
- updateExchangeFromUrl,
- getExchangeTrust,
- getExchangePaytoUri,
- acceptExchangeTermsOfService,
-} from "./operations/exchanges";
-import {
- processReserve,
- createTalerWithdrawReserve,
- forceQueryReserve,
- getFundingPaytoUris,
-} from "./operations/reserves";
-
-import { InternalWalletState } from "./operations/state";
-import { createReserve } from "./operations/reserves";
-import { processRefreshGroup, createRefreshGroup } from "./operations/refresh";
-import { processWithdrawGroup } from "./operations/withdraw";
-import { getPendingOperations } from "./operations/pending";
-import { getBalances } from "./operations/balance";
-import { acceptTip, getTipStatus, processTip } from "./operations/tip";
-import { TimerGroup } from "./util/timer";
-import { AsyncCondition } from "./util/promiseUtils";
-import { AsyncOpMemoSingle } from "./util/asyncMemo";
-import {
- PendingOperationInfo,
- PendingOperationsResponse,
- PendingOperationType,
-} from "./types/pending";
-import { WalletNotification, NotificationType } from "./types/notifications";
-import { processPurchaseQueryRefund, applyRefund } from "./operations/refund";
-import { durationMin, Duration } from "./util/time";
-import { processRecoupGroup } from "./operations/recoup";
-import { OperationFailedAndReportedError } from "./operations/errors";
-import {
- TransactionsRequest,
- TransactionsResponse,
-} from "./types/transactions";
-import { getTransactions } from "./operations/transactions";
-import { withdrawTestBalance } from "./operations/testing";
-
-const builtinCurrencies: CurrencyRecord[] = [
- {
- auditors: [
- {
- auditorPub: "BW9DC48PHQY4NH011SHHX36DZZ3Q22Y6X7FZ1VD1CMZ2PTFZ6PN0",
- baseUrl: "https://auditor.demo.taler.net/",
- expirationStamp: new Date(2027, 1).getTime(),
- },
- ],
- exchanges: [],
- fractionalDigits: 2,
- name: "KUDOS",
- },
-];
-
-const logger = new Logger("wallet.ts");
-
-/**
- * The platform-independent wallet implementation.
- */
-export class Wallet {
- private ws: InternalWalletState;
- private timerGroup: TimerGroup = new TimerGroup();
- private latch = new AsyncCondition();
- private stopped = false;
- private memoRunRetryLoop = new AsyncOpMemoSingle<void>();
-
- get db(): Database {
- return this.ws.db;
- }
-
- constructor(
- db: Database,
- http: HttpRequestLibrary,
- cryptoWorkerFactory: CryptoWorkerFactory,
- ) {
- this.ws = new InternalWalletState(db, http, cryptoWorkerFactory);
- }
-
- getExchangePaytoUri(
- exchangeBaseUrl: string,
- supportedTargetTypes: string[],
- ): Promise<string> {
- return getExchangePaytoUri(this.ws, exchangeBaseUrl, supportedTargetTypes);
- }
-
- async getWithdrawalDetailsForAmount(
- exchangeBaseUrl: string,
- amount: AmountJson,
- ): Promise<ManualWithdrawalDetails> {
- const wi = await getExchangeWithdrawalInfo(
- this.ws,
- exchangeBaseUrl,
- amount,
- );
- const paytoUris = wi.exchangeInfo.wireInfo?.accounts.map(
- (x) => x.payto_uri,
- );
- if (!paytoUris) {
- throw Error("exchange is in invalid state");
- }
- return {
- amountRaw: Amounts.stringify(amount),
- amountEffective: Amounts.stringify(wi.selectedDenoms.totalCoinValue),
- paytoUris,
- tosAccepted: wi.termsOfServiceAccepted,
- };
- }
-
- addNotificationListener(f: (n: WalletNotification) => void): void {
- this.ws.addNotificationListener(f);
- }
-
- /**
- * Execute one operation based on the pending operation info record.
- */
- async processOnePendingOperation(
- pending: PendingOperationInfo,
- forceNow = false,
- ): Promise<void> {
- logger.trace(`running pending ${JSON.stringify(pending, undefined, 2)}`);
- switch (pending.type) {
- case PendingOperationType.Bug:
- // Nothing to do, will just be displayed to the user
- return;
- case PendingOperationType.ExchangeUpdate:
- await updateExchangeFromUrl(this.ws, pending.exchangeBaseUrl, forceNow);
- break;
- case PendingOperationType.Refresh:
- await processRefreshGroup(this.ws, pending.refreshGroupId, forceNow);
- break;
- case PendingOperationType.Reserve:
- await processReserve(this.ws, pending.reservePub, forceNow);
- break;
- case PendingOperationType.Withdraw:
- await processWithdrawGroup(
- this.ws,
- pending.withdrawalGroupId,
- forceNow,
- );
- break;
- case PendingOperationType.ProposalChoice:
- // Nothing to do, user needs to accept/reject
- break;
- case PendingOperationType.ProposalDownload:
- await processDownloadProposal(this.ws, pending.proposalId, forceNow);
- break;
- case PendingOperationType.TipChoice:
- // Nothing to do, user needs to accept/reject
- break;
- case PendingOperationType.TipPickup:
- await processTip(this.ws, pending.tipId, forceNow);
- break;
- case PendingOperationType.Pay:
- await processPurchasePay(this.ws, pending.proposalId, forceNow);
- break;
- case PendingOperationType.RefundQuery:
- await processPurchaseQueryRefund(this.ws, pending.proposalId, forceNow);
- break;
- case PendingOperationType.Recoup:
- await processRecoupGroup(this.ws, pending.recoupGroupId, forceNow);
- break;
- default:
- assertUnreachable(pending);
- }
- }
-
- /**
- * Process pending operations.
- */
- public async runPending(forceNow = false): Promise<void> {
- const onlyDue = !forceNow;
- const pendingOpsResponse = await this.getPendingOperations({ onlyDue });
- for (const p of pendingOpsResponse.pendingOperations) {
- try {
- await this.processOnePendingOperation(p, forceNow);
- } catch (e) {
- if (e instanceof OperationFailedAndReportedError) {
- console.error(
- "Operation failed:",
- JSON.stringify(e.operationError, undefined, 2),
- );
- } else {
- console.error(e);
- }
- }
- }
- }
-
- /**
- * Run the wallet until there are no more pending operations that give
- * liveness left. The wallet will be in a stopped state when this function
- * returns without resolving to an exception.
- */
- public async runUntilDone(): Promise<void> {
- let done = false;
- const p = new Promise((resolve, reject) => {
- // Run this asynchronously
- this.addNotificationListener((n) => {
- if (done) {
- return;
- }
- if (
- n.type === NotificationType.WaitingForRetry &&
- n.numGivingLiveness == 0
- ) {
- done = true;
- logger.trace("no liveness-giving operations left");
- resolve();
- }
- });
- this.runRetryLoop().catch((e) => {
- console.log("exception in wallet retry loop");
- reject(e);
- });
- });
- await p;
- }
-
- /**
- * Run the wallet until there are no more pending operations that give
- * liveness left. The wallet will be in a stopped state when this function
- * returns without resolving to an exception.
- */
- public async runUntilDoneAndStop(): Promise<void> {
- await this.runUntilDone();
- logger.trace("stopping after liveness-giving operations done");
- this.stop();
- }
-
- /**
- * Process pending operations and wait for scheduled operations in
- * a loop until the wallet is stopped explicitly.
- */
- public async runRetryLoop(): Promise<void> {
- // Make sure we only run one main loop at a time.
- return this.memoRunRetryLoop.memo(async () => {
- try {
- await this.runRetryLoopImpl();
- } catch (e) {
- console.error("error during retry loop execution", e);
- throw e;
- }
- });
- }
-
- private async runRetryLoopImpl(): Promise<void> {
- while (!this.stopped) {
- const pending = await this.getPendingOperations({ onlyDue: true });
- if (pending.pendingOperations.length === 0) {
- const allPending = await this.getPendingOperations({ onlyDue: false });
- let numPending = 0;
- let numGivingLiveness = 0;
- for (const p of allPending.pendingOperations) {
- numPending++;
- if (p.givesLifeness) {
- numGivingLiveness++;
- }
- }
- let dt: Duration;
- if (
- allPending.pendingOperations.length === 0 ||
- allPending.nextRetryDelay.d_ms === Number.MAX_SAFE_INTEGER
- ) {
- // Wait for 5 seconds
- dt = { d_ms: 5000 };
- } else {
- dt = durationMin({ d_ms: 5000 }, allPending.nextRetryDelay);
- }
- const timeout = this.timerGroup.resolveAfter(dt);
- this.ws.notify({
- type: NotificationType.WaitingForRetry,
- numGivingLiveness,
- numPending,
- });
- await Promise.race([timeout, this.latch.wait()]);
- console.log("timeout done");
- } else {
- // FIXME: maybe be a bit smarter about executing these
- // operations in parallel?
- for (const p of pending.pendingOperations) {
- try {
- await this.processOnePendingOperation(p);
- } catch (e) {
- if (e instanceof OperationFailedAndReportedError) {
- logger.warn("operation processed resulted in reported error");
- } else {
- console.error("Uncaught exception", e);
- this.ws.notify({
- type: NotificationType.InternalError,
- message: "uncaught exception",
- exception: e,
- });
- }
- }
- this.ws.notify({
- type: NotificationType.PendingOperationProcessed,
- });
- }
- }
- }
- logger.trace("exiting wallet retry loop");
- }
-
- /**
- * Insert the hard-coded defaults for exchanges, coins and
- * auditors into the database, unless these defaults have
- * already been applied.
- */
- async fillDefaults(): Promise<void> {
- await this.db.runWithWriteTransaction(
- [Stores.config, Stores.currencies],
- async (tx) => {
- let applied = false;
- await tx.iter(Stores.config).forEach((x) => {
- if (x.key == "currencyDefaultsApplied" && x.value == true) {
- applied = true;
- }
- });
- if (!applied) {
- for (const c of builtinCurrencies) {
- await tx.put(Stores.currencies, c);
- }
- }
- },
- );
- }
-
- /**
- * 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.
- */
- async preparePayForUri(talerPayUri: string): Promise<PreparePayResult> {
- return preparePayForUri(this.ws, talerPayUri);
- }
-
- /**
- * Add a contract to the wallet and sign coins, and send them.
- */
- async confirmPay(
- proposalId: string,
- sessionIdOverride: string | undefined,
- ): Promise<ConfirmPayResult> {
- try {
- return await confirmPay(this.ws, proposalId, sessionIdOverride);
- } finally {
- this.latch.trigger();
- }
- }
-
- /**
- * First fetch information requred to withdraw from the reserve,
- * then deplete the reserve, withdrawing coins until it is empty.
- *
- * The returned promise resolves once the reserve is set to the
- * state DORMANT.
- */
- async processReserve(reservePub: string): Promise<void> {
- try {
- return await processReserve(this.ws, reservePub);
- } finally {
- this.latch.trigger();
- }
- }
-
- /**
- * Create a reserve, but do not flag it as confirmed yet.
- *
- * Adds the corresponding exchange as a trusted exchange if it is neither
- * audited nor trusted already.
- */
- async acceptManualWithdrawal(
- exchangeBaseUrl: string,
- amount: AmountJson,
- ): Promise<AcceptManualWithdrawalResult> {
- try {
- const resp = await createReserve(this.ws, {
- amount,
- exchange: exchangeBaseUrl,
- });
- const exchangePaytoUris = await this.db.runWithReadTransaction(
- [Stores.exchanges, Stores.reserves],
- (tx) => getFundingPaytoUris(tx, resp.reservePub),
- );
- return {
- reservePub: resp.reservePub,
- exchangePaytoUris,
- };
- } finally {
- this.latch.trigger();
- }
- }
-
- /**
- * Check if and how an exchange is trusted and/or audited.
- */
- async getExchangeTrust(
- exchangeInfo: ExchangeRecord,
- ): Promise<{ isTrusted: boolean; isAudited: boolean }> {
- return getExchangeTrust(this.ws, exchangeInfo);
- }
-
- async getWithdrawalDetailsForUri(talerWithdrawUri: string): Promise<WithdrawUriInfoResponse> {
- return getWithdrawalDetailsForUri(this.ws, talerWithdrawUri);
- }
-
- /**
- * Update or add exchange DB entry by fetching the /keys and /wire information.
- * Optionally link the reserve entry to the new or existing
- * exchange entry in then DB.
- */
- async updateExchangeFromUrl(
- baseUrl: string,
- force = false,
- ): Promise<ExchangeRecord> {
- try {
- return updateExchangeFromUrl(this.ws, baseUrl, force);
- } finally {
- this.latch.trigger();
- }
- }
-
- async getExchangeTos(exchangeBaseUrl: string): Promise<GetExchangeTosResult> {
- const exchange = await this.updateExchangeFromUrl(exchangeBaseUrl);
- const tos = exchange.termsOfServiceText;
- const currentEtag = exchange.termsOfServiceLastEtag;
- if (!tos || !currentEtag) {
- throw Error("exchange is in invalid state");
- }
- return {
- acceptedEtag: exchange.termsOfServiceAcceptedEtag,
- currentEtag,
- tos,
- };
- }
-
- /**
- * Get detailed balance information, sliced by exchange and by currency.
- */
- async getBalances(): Promise<BalancesResponse> {
- return this.ws.memoGetBalance.memo(() => getBalances(this.ws));
- }
-
- async refresh(oldCoinPub: string): Promise<void> {
- try {
- const refreshGroupId = await this.db.runWithWriteTransaction(
- [Stores.refreshGroups],
- async (tx) => {
- return await createRefreshGroup(
- this.ws,
- tx,
- [{ coinPub: oldCoinPub }],
- RefreshReason.Manual,
- );
- },
- );
- await processRefreshGroup(this.ws, refreshGroupId.refreshGroupId);
- } catch (e) {
- this.latch.trigger();
- }
- }
-
- async findExchange(
- exchangeBaseUrl: string,
- ): Promise<ExchangeRecord | undefined> {
- return await this.db.get(Stores.exchanges, exchangeBaseUrl);
- }
-
- async getPendingOperations({ onlyDue = false } = {}): Promise<
- PendingOperationsResponse
- > {
- return this.ws.memoGetPending.memo(() =>
- getPendingOperations(this.ws, { onlyDue }),
- );
- }
-
- async acceptExchangeTermsOfService(
- exchangeBaseUrl: string,
- etag: string | undefined,
- ): Promise<void> {
- return acceptExchangeTermsOfService(this.ws, exchangeBaseUrl, etag);
- }
-
- async getDenoms(exchangeUrl: string): Promise<DenominationRecord[]> {
- const denoms = await this.db
- .iterIndex(Stores.denominations.exchangeBaseUrlIndex, exchangeUrl)
- .toArray();
- return denoms;
- }
-
- /**
- * Get all exchanges known to the exchange.
- *
- * @deprecated Use getExchanges instead
- */
- async getExchangeRecords(): Promise<ExchangeRecord[]> {
- return await this.db.iter(Stores.exchanges).toArray();
- }
-
- async getExchanges(): Promise<ExchangesListRespose> {
- const exchanges: (ExchangeListItem | undefined)[] = await this.db
- .iter(Stores.exchanges)
- .map((x) => {
- const details = x.details;
- if (!details) {
- return undefined;
- }
- if (!x.addComplete) {
- return undefined;
- }
- if (!x.wireInfo) {
- return undefined;
- }
- return {
- exchangeBaseUrl: x.baseUrl,
- currency: details.currency,
- paytoUris: x.wireInfo.accounts.map((x) => x.payto_uri),
- };
- });
- return {
- exchanges: exchanges.filter((x) => !!x) as ExchangeListItem[],
- };
- }
-
- async getCurrencies(): Promise<CurrencyRecord[]> {
- return await this.db.iter(Stores.currencies).toArray();
- }
-
- async updateCurrency(currencyRecord: CurrencyRecord): Promise<void> {
- logger.trace("updating currency to", currencyRecord);
- await this.db.put(Stores.currencies, currencyRecord);
- }
-
- async getReserves(exchangeBaseUrl?: string): Promise<ReserveRecord[]> {
- if (exchangeBaseUrl) {
- return await this.db
- .iter(Stores.reserves)
- .filter((r) => r.exchangeBaseUrl === exchangeBaseUrl);
- } else {
- return await this.db.iter(Stores.reserves).toArray();
- }
- }
-
- async getCoinsForExchange(exchangeBaseUrl: string): Promise<CoinRecord[]> {
- return await this.db
- .iter(Stores.coins)
- .filter((c) => c.exchangeBaseUrl === exchangeBaseUrl);
- }
-
- async getCoins(): Promise<CoinRecord[]> {
- return await this.db.iter(Stores.coins).toArray();
- }
-
- /**
- * Stop ongoing processing.
- */
- stop(): void {
- this.stopped = true;
- this.timerGroup.stopCurrentAndFutureTimers();
- this.ws.cryptoApi.stop();
- }
-
- async getSenderWireInfos(): Promise<SenderWireInfos> {
- const m: { [url: string]: Set<string> } = {};
-
- await this.db.iter(Stores.exchanges).forEach((x) => {
- const wi = x.wireInfo;
- if (!wi) {
- return;
- }
- const s = (m[x.baseUrl] = m[x.baseUrl] || new Set());
- Object.keys(wi.feesForType).map((k) => s.add(k));
- });
-
- const exchangeWireTypes: { [url: string]: string[] } = {};
- Object.keys(m).map((e) => {
- exchangeWireTypes[e] = Array.from(m[e]);
- });
-
- const senderWiresSet: Set<string> = new Set();
- await this.db.iter(Stores.senderWires).forEach((x) => {
- senderWiresSet.add(x.paytoUri);
- });
-
- const senderWires: string[] = Array.from(senderWiresSet);
-
- return {
- exchangeWireTypes,
- senderWires,
- };
- }
-
- /**
- * Trigger paying coins back into the user's account.
- */
- async returnCoins(req: ReturnCoinsRequest): Promise<void> {
- throw Error("not implemented");
- }
-
- /**
- * Accept a refund, return the contract hash for the contract
- * that was involved in the refund.
- */
- async applyRefund(
- talerRefundUri: string,
- ): Promise<{ contractTermsHash: string; proposalId: string }> {
- return applyRefund(this.ws, talerRefundUri);
- }
-
- async getPurchase(
- contractTermsHash: string,
- ): Promise<PurchaseRecord | undefined> {
- return this.db.get(Stores.purchases, contractTermsHash);
- }
-
- async acceptTip(talerTipUri: string): Promise<void> {
- try {
- return acceptTip(this.ws, talerTipUri);
- } catch (e) {
- this.latch.trigger();
- }
- }
-
- async getTipStatus(talerTipUri: string): Promise<TipStatus> {
- return getTipStatus(this.ws, talerTipUri);
- }
-
- async abortFailedPayment(contractTermsHash: string): Promise<void> {
- throw Error("not implemented");
- }
-
- /**
- * Inform the wallet that the status of a reserve has changed (e.g. due to a
- * confirmation from the bank.).
- */
- public async handleNotifyReserve(): Promise<void> {
- const reserves = await this.db.iter(Stores.reserves).toArray();
- for (const r of reserves) {
- if (r.reserveStatus === ReserveRecordStatus.WAIT_CONFIRM_BANK) {
- try {
- this.processReserve(r.reservePub);
- } catch (e) {
- console.error(e);
- }
- }
- }
- }
-
- /**
- * Remove unreferenced / expired data from the wallet's database
- * based on the current system time.
- */
- async collectGarbage(): Promise<void> {
- // FIXME(#5845)
- // We currently do not garbage-collect the wallet database. This might change
- // after the feature has been properly re-designed, and we have come up with a
- // strategy to test it.
- }
-
- async acceptWithdrawal(
- talerWithdrawUri: string,
- selectedExchange: string,
- ): Promise<AcceptWithdrawalResponse> {
- try {
- return createTalerWithdrawReserve(
- this.ws,
- talerWithdrawUri,
- selectedExchange,
- );
- } finally {
- this.latch.trigger();
- }
- }
-
- async updateReserve(reservePub: string): Promise<ReserveRecord | undefined> {
- await forceQueryReserve(this.ws, reservePub);
- return await this.ws.db.get(Stores.reserves, reservePub);
- }
-
- async getReserve(reservePub: string): Promise<ReserveRecord | undefined> {
- return await this.ws.db.get(Stores.reserves, reservePub);
- }
-
- async refuseProposal(proposalId: string): Promise<void> {
- return refuseProposal(this.ws, proposalId);
- }
-
- async getPurchaseDetails(proposalId: string): Promise<PurchaseDetails> {
- const purchase = await this.db.get(Stores.purchases, proposalId);
- if (!purchase) {
- throw Error("unknown purchase");
- }
- const refundsDoneAmounts = Object.values(purchase.refunds)
- .filter((x) => x.type === RefundState.Applied)
- .map((x) => x.refundAmount);
-
- const refundsPendingAmounts = Object.values(purchase.refunds)
- .filter((x) => x.type === RefundState.Pending)
- .map((x) => x.refundAmount);
- const totalRefundAmount = Amounts.sum([
- ...refundsDoneAmounts,
- ...refundsPendingAmounts,
- ]).amount;
- const refundsDoneFees = Object.values(purchase.refunds)
- .filter((x) => x.type === RefundState.Applied)
- .map((x) => x.refundFee);
- const refundsPendingFees = Object.values(purchase.refunds)
- .filter((x) => x.type === RefundState.Pending)
- .map((x) => x.refundFee);
- const totalRefundFees = Amounts.sum([
- ...refundsDoneFees,
- ...refundsPendingFees,
- ]).amount;
- const totalFees = totalRefundFees;
- return {
- contractTerms: JSON.parse(purchase.contractTermsRaw),
- hasRefund: purchase.timestampLastRefundStatus !== undefined,
- totalRefundAmount: totalRefundAmount,
- totalRefundAndRefreshFees: totalFees,
- };
- }
-
- benchmarkCrypto(repetitions: number): Promise<BenchmarkResult> {
- return this.ws.cryptoApi.benchmark(repetitions);
- }
-
- async setCoinSuspended(coinPub: string, suspended: boolean): Promise<void> {
- await this.db.runWithWriteTransaction([Stores.coins], async (tx) => {
- const c = await tx.get(Stores.coins, coinPub);
- if (!c) {
- logger.warn(`coin ${coinPub} not found, won't suspend`);
- return;
- }
- c.suspended = suspended;
- await tx.put(Stores.coins, c);
- });
- }
-
- /**
- * Dump the public information of coins we have in an easy-to-process format.
- */
- async dumpCoins(): Promise<CoinDumpJson> {
- const coins = await this.db.iter(Stores.coins).toArray();
- const coinsJson: CoinDumpJson = { coins: [] };
- for (const c of coins) {
- const denom = await this.db.get(Stores.denominations, [
- c.exchangeBaseUrl,
- c.denomPub,
- ]);
- if (!denom) {
- console.error("no denom session found for coin");
- continue;
- }
- const cs = c.coinSource;
- let refreshParentCoinPub: string | undefined;
- if (cs.type == CoinSourceType.Refresh) {
- refreshParentCoinPub = cs.oldCoinPub;
- }
- let withdrawalReservePub: string | undefined;
- if (cs.type == CoinSourceType.Withdraw) {
- const ws = await this.db.get(
- Stores.withdrawalGroups,
- cs.withdrawalGroupId,
- );
- if (!ws) {
- console.error("no withdrawal session found for coin");
- continue;
- }
- if (ws.source.type == "reserve") {
- withdrawalReservePub = ws.source.reservePub;
- }
- }
- coinsJson.coins.push({
- coin_pub: c.coinPub,
- denom_pub: c.denomPub,
- denom_pub_hash: c.denomPubHash,
- denom_value: Amounts.stringify(denom.value),
- exchange_base_url: c.exchangeBaseUrl,
- refresh_parent_coin_pub: refreshParentCoinPub,
- remaining_value: Amounts.stringify(c.currentAmount),
- withdrawal_reserve_pub: withdrawalReservePub,
- coin_suspended: c.suspended,
- });
- }
- return coinsJson;
- }
-
- async getTransactions(
- request: TransactionsRequest,
- ): Promise<TransactionsResponse> {
- return getTransactions(this.ws, request);
- }
-
-
- async withdrawTestBalance(
- amount = "TESTKUDOS:10",
- bankBaseUrl = "https://bank.test.taler.net/",
- exchangeBaseUrl = "https://exchange.test.taler.net/",
- ): Promise<void> {
- await withdrawTestBalance(this.ws, amount, bankBaseUrl, exchangeBaseUrl);
- }
-}
diff --git a/src/walletCoreApiHandler.ts b/src/walletCoreApiHandler.ts
deleted file mode 100644
index 7ab6a6284..000000000
--- a/src/walletCoreApiHandler.ts
+++ /dev/null
@@ -1,325 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2020 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 { Wallet } from "./wallet";
-import {
- OperationFailedError,
- OperationFailedAndReportedError,
- makeErrorDetails,
-} from "./operations/errors";
-import { TalerErrorCode } from "./TalerErrorCode";
-import { codecForTransactionsRequest } from "./types/transactions";
-import {
- makeCodecForObject,
- codecForString,
- Codec,
- makeCodecOptional,
-} from "./util/codec";
-import { Amounts } from "./util/amounts";
-import { OperationErrorDetails } from "./types/walletTypes";
-
-interface AddExchangeRequest {
- exchangeBaseUrl: string;
-}
-
-const codecForAddExchangeRequest = (): Codec<AddExchangeRequest> =>
- makeCodecForObject<AddExchangeRequest>()
- .property("exchangeBaseUrl", codecForString)
- .build("AddExchangeRequest");
-
-interface GetExchangeTosRequest {
- exchangeBaseUrl: string;
-}
-
-const codecForGetExchangeTosRequest = (): Codec<GetExchangeTosRequest> =>
- makeCodecForObject<GetExchangeTosRequest>()
- .property("exchangeBaseUrl", codecForString)
- .build("GetExchangeTosRequest");
-
-interface AcceptManualWithdrawalRequest {
- exchangeBaseUrl: string;
- amount: string;
-}
-
-const codecForAcceptManualWithdrawalRequet = (): Codec<
- AcceptManualWithdrawalRequest
-> =>
- makeCodecForObject<AcceptManualWithdrawalRequest>()
- .property("exchangeBaseUrl", codecForString)
- .property("amount", codecForString)
- .build("AcceptManualWithdrawalRequest");
-
-interface GetWithdrawalDetailsForAmountRequest {
- exchangeBaseUrl: string;
- amount: string;
-}
-
-interface AcceptBankIntegratedWithdrawalRequest {
- talerWithdrawUri: string;
- exchangeBaseUrl: string;
-}
-
-const codecForAcceptBankIntegratedWithdrawalRequest = (): Codec<
- AcceptBankIntegratedWithdrawalRequest
-> =>
- makeCodecForObject<AcceptBankIntegratedWithdrawalRequest>()
- .property("exchangeBaseUrl", codecForString)
- .property("talerWithdrawUri", codecForString)
- .build("AcceptBankIntegratedWithdrawalRequest");
-
-const codecForGetWithdrawalDetailsForAmountRequest = (): Codec<
- GetWithdrawalDetailsForAmountRequest
-> =>
- makeCodecForObject<GetWithdrawalDetailsForAmountRequest>()
- .property("exchangeBaseUrl", codecForString)
- .property("amount", codecForString)
- .build("GetWithdrawalDetailsForAmountRequest");
-
-interface AcceptExchangeTosRequest {
- exchangeBaseUrl: string;
- etag: string;
-}
-
-const codecForAcceptExchangeTosRequest = (): Codec<AcceptExchangeTosRequest> =>
- makeCodecForObject<AcceptExchangeTosRequest>()
- .property("exchangeBaseUrl", codecForString)
- .property("etag", codecForString)
- .build("AcceptExchangeTosRequest");
-
-interface ApplyRefundRequest {
- talerRefundUri: string;
-}
-
-const codecForApplyRefundRequest = (): Codec<ApplyRefundRequest> =>
- makeCodecForObject<ApplyRefundRequest>()
- .property("talerRefundUri", codecForString)
- .build("ApplyRefundRequest");
-
-interface GetWithdrawalDetailsForUriRequest {
- talerWithdrawUri: string;
-}
-
-const codecForGetWithdrawalDetailsForUri = (): Codec<
- GetWithdrawalDetailsForUriRequest
-> =>
- makeCodecForObject<GetWithdrawalDetailsForUriRequest>()
- .property("talerWithdrawUri", codecForString)
- .build("GetWithdrawalDetailsForUriRequest");
-
-interface AbortProposalRequest {
- proposalId: string;
-}
-
-const codecForAbortProposalRequest = (): Codec<AbortProposalRequest> =>
- makeCodecForObject<AbortProposalRequest>()
- .property("proposalId", codecForString)
- .build("AbortProposalRequest");
-
-interface PreparePayRequest {
- talerPayUri: string;
-}
-
-const codecForPreparePayRequest = (): Codec<PreparePayRequest> =>
- makeCodecForObject<PreparePayRequest>()
- .property("talerPayUri", codecForString)
- .build("PreparePay");
-
-interface ConfirmPayRequest {
- proposalId: string;
- sessionId?: string;
-}
-
-const codecForConfirmPayRequest = (): Codec<ConfirmPayRequest> =>
- makeCodecForObject<ConfirmPayRequest>()
- .property("proposalId", codecForString)
- .property("sessionId", makeCodecOptional(codecForString))
- .build("ConfirmPay");
-
-/**
- * Implementation of the "wallet-core" API.
- */
-
-async function dispatchRequestInternal(
- wallet: Wallet,
- operation: string,
- payload: unknown,
-): Promise<Record<string, any>> {
- switch (operation) {
- case "withdrawTestkudos":
- await wallet.withdrawTestBalance();
- return {};
- case "getTransactions": {
- const req = codecForTransactionsRequest().decode(payload);
- return await wallet.getTransactions(req);
- }
- case "addExchange": {
- const req = codecForAddExchangeRequest().decode(payload);
- await wallet.updateExchangeFromUrl(req.exchangeBaseUrl);
- return {};
- }
- case "listExchanges": {
- return await wallet.getExchanges();
- }
- case "getWithdrawalDetailsForUri": {
- const req = codecForGetWithdrawalDetailsForUri().decode(payload);
- return await wallet.getWithdrawalDetailsForUri(req.talerWithdrawUri);
- }
- case "acceptManualWithdrawal": {
- const req = codecForAcceptManualWithdrawalRequet().decode(payload);
- const res = await wallet.acceptManualWithdrawal(
- req.exchangeBaseUrl,
- Amounts.parseOrThrow(req.amount),
- );
- return res;
- }
- case "getWithdrawalDetailsForAmount": {
- const req = codecForGetWithdrawalDetailsForAmountRequest().decode(
- payload,
- );
- return await wallet.getWithdrawalDetailsForAmount(
- req.exchangeBaseUrl,
- Amounts.parseOrThrow(req.amount),
- );
- }
- case "getBalances": {
- return await wallet.getBalances();
- }
- case "getPendingOperations": {
- return await wallet.getPendingOperations();
- }
- case "setExchangeTosAccepted": {
- const req = codecForAcceptExchangeTosRequest().decode(payload);
- await wallet.acceptExchangeTermsOfService(
- req.exchangeBaseUrl,
- req.etag,
- );
- return {};
- }
- case "applyRefund": {
- const req = codecForApplyRefundRequest().decode(payload);
- return await wallet.applyRefund(req.talerRefundUri);
- }
- case "acceptBankIntegratedWithdrawal": {
- const req = codecForAcceptBankIntegratedWithdrawalRequest().decode(
- payload,
- );
- return await wallet.acceptWithdrawal(
- req.talerWithdrawUri,
- req.exchangeBaseUrl,
- );
- }
- case "getExchangeTos": {
- const req = codecForGetExchangeTosRequest().decode(payload);
- return wallet.getExchangeTos(req.exchangeBaseUrl);
- }
- case "abortProposal": {
- const req = codecForAbortProposalRequest().decode(payload);
- await wallet.refuseProposal(req.proposalId);
- return {};
- }
- case "retryPendingNow": {
- await wallet.runPending(true);
- return {};
- }
- case "preparePay": {
- const req = codecForPreparePayRequest().decode(payload);
- return await wallet.preparePayForUri(req.talerPayUri);
- }
- case "confirmPay": {
- const req = codecForConfirmPayRequest().decode(payload);
- return await wallet.confirmPay(req.proposalId, req.sessionId);
- }
- }
- throw OperationFailedError.fromCode(
- TalerErrorCode.WALLET_CORE_API_OPERATION_UNKNOWN,
- "unknown operation",
- {
- operation,
- },
- );
-}
-
-export type CoreApiResponse =
- | CoreApiResponseSuccess
- | CoreApiResponseError;
-
-export type CoreApiEnvelope =
- | CoreApiResponse
- | CoreApiNotification;
-
-export interface CoreApiNotification {
- type: "notification";
- payload: unknown;
-}
-
-export interface CoreApiResponseSuccess {
- // To distinguish the message from notifications
- type: "response";
- operation: string,
- id: string;
- result: unknown;
-}
-
-export interface CoreApiResponseError {
- // To distinguish the message from notifications
- type: "error";
- operation: string,
- id: string;
- error: OperationErrorDetails;
-}
-
-/**
- * Handle a request to the wallet-core API.
- */
-export async function handleCoreApiRequest(
- w: Wallet,
- operation: string,
- id: string,
- payload: unknown,
-): Promise<CoreApiResponse> {
- try {
- const result = await dispatchRequestInternal(w, operation, payload);
- return {
- type: "response",
- operation,
- id,
- result,
- };
- } catch (e) {
- if (
- e instanceof OperationFailedError ||
- e instanceof OperationFailedAndReportedError
- ) {
- return {
- type: "error",
- operation,
- id,
- error: e.operationError,
- };
- } else {
- return {
- type: "error",
- operation,
- id,
- error: makeErrorDetails(
- TalerErrorCode.WALLET_UNEXPECTED_EXCEPTION,
- `unexpected exception: ${e}`,
- {},
- ),
- };
- }
- }
-}
diff --git a/src/webex/background.ts b/src/webex/background.ts
deleted file mode 100644
index dbc540df4..000000000
--- a/src/webex/background.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Entry point for the background page.
- *
- * @author Florian Dold
- */
-
-/**
- * Imports.
- */
-import { wxMain } from "./wxBackend";
-
-window.addEventListener("load", () => {
- wxMain();
-});
diff --git a/src/webex/chromeBadge.ts b/src/webex/chromeBadge.ts
deleted file mode 100644
index 7bc5d368d..000000000
--- a/src/webex/chromeBadge.ts
+++ /dev/null
@@ -1,288 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 INRIA
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-import { isFirefox } from "./compat";
-
-/**
- * Polyfill for requestAnimationFrame, which
- * doesn't work from a background page.
- */
-function rAF(cb: (ts: number) => void): void {
- window.setTimeout(() => {
- cb(performance.now());
- }, 100 /* 100 ms delay between frames */);
-}
-
-/**
- * Badge for Chrome that renders a Taler logo with a rotating ring if some
- * background activity is happening.
- */
-export class ChromeBadge {
- private canvas: HTMLCanvasElement;
- private ctx: CanvasRenderingContext2D;
- /**
- * True if animation running. The animation
- * might still be running even if we're not busy anymore,
- * just to transition to the "normal" state in a animated way.
- */
- private animationRunning = false;
-
- /**
- * Is the wallet still busy? Note that we do not stop the
- * animation immediately when the wallet goes idle, but
- * instead slowly close the gap.
- */
- private isBusy = false;
-
- /**
- * Current rotation angle, ranges from 0 to rotationAngleMax.
- */
- private rotationAngle = 0;
-
- /**
- * While animating, how wide is the current gap in the circle?
- * Ranges from 0 to openMax.
- */
- private gapWidth = 0;
-
- /**
- * Should we show the notification dot?
- */
- private hasNotification = false;
-
- /**
- * Maximum value for our rotationAngle, corresponds to 2 Pi.
- */
- static rotationAngleMax = 1000;
-
- /**
- * How fast do we rotate? Given in rotation angle (relative to rotationAngleMax) per millisecond.
- */
- static rotationSpeed = 0.5;
-
- /**
- * How fast to we open? Given in rotation angle (relative to rotationAngleMax) per millisecond.
- */
- static openSpeed = 0.15;
-
- /**
- * How fast to we close? Given as a multiplication factor per frame update.
- */
- static closeSpeed = 0.7;
-
- /**
- * How far do we open? Given relative to rotationAngleMax.
- */
- static openMax = 100;
-
- constructor(window?: Window) {
- // Allow injecting another window for testing
- const bg = window || chrome.extension.getBackgroundPage();
- if (!bg) {
- throw Error("no window available");
- }
- this.canvas = bg.document.createElement("canvas");
- // Note: changing the width here means changing the font
- // size in draw() as well!
- this.canvas.width = 32;
- this.canvas.height = 32;
- const ctx = this.canvas.getContext("2d");
- if (!ctx) {
- throw Error("unable to get canvas context");
- }
- this.ctx = ctx;
- this.draw();
- }
-
- /**
- * Draw the badge based on the current state.
- */
- private draw(): void {
- this.ctx.setTransform(1, 0, 0, 1, 0, 0);
- this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
-
- this.ctx.translate(this.canvas.width / 2, this.canvas.height / 2);
-
- this.ctx.beginPath();
- this.ctx.arc(0, 0, this.canvas.width / 2 - 2, 0, 2 * Math.PI);
- this.ctx.fillStyle = "white";
- this.ctx.fill();
-
- // move into the center, off by 2 for aligning the "T" with the bottom
- // of the circle.
- this.ctx.translate(0, 2);
-
- // pick sans-serif font; note: 14px is based on the 32px width above!
- this.ctx.font = "bold 24px sans-serif";
- // draw the "T" perfectly centered (x and y) to the current position
- this.ctx.textAlign = "center";
- this.ctx.textBaseline = "middle";
- this.ctx.fillStyle = "black";
- this.ctx.fillText("T", 0, 0);
- // now move really into the center
- this.ctx.translate(0, -2);
- // start drawing the (possibly open) circle
- this.ctx.beginPath();
- this.ctx.lineWidth = 2.5;
- if (this.animationRunning) {
- /* Draw circle around the "T" with an opening of this.gapWidth */
- const aMax = ChromeBadge.rotationAngleMax;
- const startAngle = (this.rotationAngle / aMax) * Math.PI * 2;
- const stopAngle =
- ((this.rotationAngle + aMax - this.gapWidth) / aMax) * Math.PI * 2;
- this.ctx.arc(
- 0,
- 0,
- this.canvas.width / 2 - 2,
- /* radius */ startAngle,
- stopAngle,
- false,
- );
- } else {
- /* Draw full circle */
- this.ctx.arc(
- 0,
- 0,
- this.canvas.width / 2 - 2 /* radius */,
- 0,
- Math.PI * 2,
- false,
- );
- }
- this.ctx.stroke();
- // go back to the origin
- this.ctx.translate(-this.canvas.width / 2, -this.canvas.height / 2);
-
- if (this.hasNotification) {
- // We draw a circle with a soft border in the
- // lower right corner.
- const r = 8;
- const cw = this.canvas.width;
- const ch = this.canvas.height;
- this.ctx.beginPath();
- this.ctx.arc(cw - r, ch - r, r, 0, 2 * Math.PI, false);
- const gradient = this.ctx.createRadialGradient(
- cw - r,
- ch - r,
- r,
- cw - r,
- ch - r,
- 5,
- );
- gradient.addColorStop(0, "rgba(255, 255, 255, 1)");
- gradient.addColorStop(1, "blue");
- this.ctx.fillStyle = gradient;
- this.ctx.fill();
- }
-
- // Allow running outside the extension for testing
- // tslint:disable-next-line:no-string-literal
- if (window["chrome"] && window.chrome["browserAction"]) {
- try {
- const imageData = this.ctx.getImageData(
- 0,
- 0,
- this.canvas.width,
- this.canvas.height,
- );
- chrome.browserAction.setIcon({ imageData });
- } catch (e) {
- // Might fail if browser has over-eager canvas fingerprinting countermeasures.
- // There's nothing we can do then ...
- }
- }
- }
-
- private animate(): void {
- if (this.animationRunning) {
- return;
- }
- if (isFirefox()) {
- // Firefox does not support badge animations properly
- return;
- }
- this.animationRunning = true;
- let start: number | undefined;
- const step = (timestamp: number): void => {
- if (!this.animationRunning) {
- return;
- }
- if (!start) {
- start = timestamp;
- }
- if (!this.isBusy && 0 === this.gapWidth) {
- // stop if we're close enough to origin
- this.rotationAngle = 0;
- } else {
- this.rotationAngle =
- (this.rotationAngle +
- (timestamp - start) * ChromeBadge.rotationSpeed) %
- ChromeBadge.rotationAngleMax;
- }
- if (this.isBusy) {
- if (this.gapWidth < ChromeBadge.openMax) {
- this.gapWidth += ChromeBadge.openSpeed * (timestamp - start);
- }
- if (this.gapWidth > ChromeBadge.openMax) {
- this.gapWidth = ChromeBadge.openMax;
- }
- } else {
- if (this.gapWidth > 0) {
- this.gapWidth--;
- this.gapWidth *= ChromeBadge.closeSpeed;
- }
- }
-
- if (this.isBusy || this.gapWidth > 0) {
- start = timestamp;
- rAF(step);
- } else {
- this.animationRunning = false;
- }
- this.draw();
- };
- rAF(step);
- }
-
- /**
- * Draw the badge such that it shows the
- * user that something happened (balance changed).
- */
- showNotification(): void {
- this.hasNotification = true;
- this.draw();
- }
-
- /**
- * Draw the badge without the notification mark.
- */
- clearNotification(): void {
- this.hasNotification = false;
- this.draw();
- }
-
- startBusy(): void {
- if (this.isBusy) {
- return;
- }
- this.isBusy = true;
- this.animate();
- }
-
- stopBusy(): void {
- this.isBusy = false;
- }
-}
diff --git a/src/webex/compat.ts b/src/webex/compat.ts
deleted file mode 100644
index 4635abd80..000000000
--- a/src/webex/compat.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- This file is part of TALER
- (C) 2017 INRIA
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Compatibility helpers needed for browsers that don't implement
- * WebExtension APIs consistently.
- */
-
-export function isFirefox(): boolean {
- const rt = chrome.runtime as any;
- if (typeof rt.getBrowserInfo === "function") {
- return true;
- }
- return false;
-}
-
-/**
- * Check if we are running under nodejs.
- */
-export function isNode(): boolean {
- return typeof process !== "undefined" && process.release.name === "node";
-}
-
-/**
- * Compatibility API that works on multiple browsers.
- */
-export interface CrossBrowserPermissionsApi {
- contains(
- permissions: chrome.permissions.Permissions,
- callback: (result: boolean) => void,
- ): void;
-
- addPermissionsListener(
- callback: (permissions: chrome.permissions.Permissions) => void,
- ): void;
-
- request(
- permissions: chrome.permissions.Permissions,
- callback?: (granted: boolean) => void,
- ): void;
-
- remove(
- permissions: chrome.permissions.Permissions,
- callback?: (removed: boolean) => void,
- ): void;
-}
-
-export function getPermissionsApi(): CrossBrowserPermissionsApi {
- const myBrowser = (globalThis as any).browser;
- if (
- typeof myBrowser === "object" &&
- typeof myBrowser.permissions === "object"
- ) {
- return {
- addPermissionsListener: () => {
- // Not supported yet.
- },
- contains: myBrowser.permissions.contains,
- request: myBrowser.permissions.request,
- remove: myBrowser.permissions.remove,
- };
- } else {
- return {
- addPermissionsListener: chrome.permissions.onAdded.addListener.bind(
- chrome.permissions.onAdded,
- ),
- contains: chrome.permissions.contains,
- request: chrome.permissions.request,
- remove: chrome.permissions.remove,
- };
- }
-}
diff --git a/src/webex/i18n-test.tsx b/src/webex/i18n-test.tsx
deleted file mode 100644
index 4a1c40254..000000000
--- a/src/webex/i18n-test.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2020 Taler Systems SA
-
- 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 test from "ava";
-import { internalSetStrings, str, Translate } from "./i18n";
-import { strings } from "../i18n/strings";
-import React from "react";
-import { render } from "enzyme";
-import { configure } from "enzyme";
-import Adapter from "enzyme-adapter-react-16";
-
-configure({ adapter: new Adapter() });
-
-const testStrings = {
- domain: "messages",
- locale_data: {
- messages: {
- str1: ["foo1"],
- str2: [""],
- "str3 %1$s / %2$s": ["foo3 %2$s ; %1$s"],
- "": {
- domain: "messages",
- plural_forms: "nplurals=2; plural=(n != 1);",
- lang: "",
- },
- },
- },
-};
-
-test("str translation", (t) => {
- // Alias, so we nly use the function for lookups, not for string extranction.
- const strAlias = str;
- const TranslateAlias = Translate;
- internalSetStrings(testStrings);
- t.is(strAlias`str1`, "foo1");
- t.is(strAlias`str2`, "str2");
- const a = "a";
- const b = "b";
- t.is(strAlias`str3 ${a} / ${b}`, "foo3 b ; a");
- const r = render(<TranslateAlias>str1</TranslateAlias>);
- t.is(r.text(), "foo1");
-
- const r2 = render(
- <TranslateAlias>
- str3 <span>{a}</span> / <span>{b}</span>
- </TranslateAlias>,
- );
- t.is(r2.text(), "foo3 b ; a");
-
- t.pass();
-});
-
-test("existing str translation", (t) => {
- internalSetStrings(strings);
- t.pass();
-});
diff --git a/src/webex/i18n.tsx b/src/webex/i18n.tsx
deleted file mode 100644
index 6b5c2318d..000000000
--- a/src/webex/i18n.tsx
+++ /dev/null
@@ -1,250 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Translation helpers for React components and template literals.
- */
-
-/**
- * Imports.
- */
-import { strings } from "../i18n/strings";
-
-// @ts-ignore: no type decl for this library
-import * as jedLib from "jed";
-
-import * as React from "react";
-
-let jed = setupJed();
-
-const enableTracing = false;
-
-/**
- * Set up jed library for internationalization,
- * based on browser language settings.
- */
-function setupJed(): any {
- let lang: string;
- try {
- lang = chrome.i18n.getUILanguage();
- // Chrome gives e.g. "en-US", but Firefox gives us "en_US"
- lang = lang.replace("_", "-");
- } catch (e) {
- lang = "en";
- console.warn("i18n default language not available");
- }
-
- if (!strings[lang]) {
- lang = "en-US";
- console.log(`language ${lang} not found, defaulting to english`);
- }
- return new jedLib.Jed(strings[lang]);
-}
-
-/**
- * Use different translations for testing. Should not be used outside
- * of test cases.
- */
-export function internalSetStrings(langStrings: any): void {
- jed = new jedLib.Jed(langStrings);
-}
-
-/**
- * Convert template strings to a msgid
- */
-function toI18nString(stringSeq: ReadonlyArray<string>): string {
- let s = "";
- for (let i = 0; i < stringSeq.length; i++) {
- s += stringSeq[i];
- if (i < stringSeq.length - 1) {
- s += `%${i + 1}$s`;
- }
- }
- return s;
-}
-
-/**
- * Internationalize a string template with arbitrary serialized values.
- */
-export function str(stringSeq: TemplateStringsArray, ...values: any[]): string {
- const s = toI18nString(stringSeq);
- const tr = jed
- .translate(s)
- .ifPlural(1, s)
- .fetch(...values);
- return tr;
-}
-
-interface TranslateSwitchProps {
- target: number;
-}
-
-function stringifyChildren(children: any): string {
- let n = 1;
- const ss = React.Children.map(children, (c) => {
- if (typeof c === "string") {
- return c;
- }
- return `%${n++}$s`;
- });
- const s = ss.join("").replace(/ +/g, " ").trim();
- enableTracing && console.log("translation lookup", JSON.stringify(s));
- return s;
-}
-
-interface TranslateProps {
- /**
- * Component that the translated element should be wrapped in.
- * Defaults to "div".
- */
- wrap?: any;
-
- /**
- * Props to give to the wrapped component.
- */
- wrapProps?: any;
-}
-
-function getTranslatedChildren(
- translation: string,
- children: React.ReactNode,
-): React.ReactNode[] {
- const tr = translation.split(/%(\d+)\$s/);
- const childArray = React.Children.toArray(children);
- // Merge consecutive string children.
- const placeholderChildren = [];
- for (let i = 0; i < childArray.length; i++) {
- const x = childArray[i];
- if (x === undefined) {
- continue;
- } else if (typeof x === "string") {
- continue;
- } else {
- placeholderChildren.push(x);
- }
- }
- const result = [];
- for (let i = 0; i < tr.length; i++) {
- if (i % 2 == 0) {
- // Text
- result.push(tr[i]);
- } else {
- const childIdx = Number.parseInt(tr[i]) - 1;
- result.push(placeholderChildren[childIdx]);
- }
- }
- return result;
-}
-
-/**
- * Translate text node children of this component.
- * If a child component might produce a text node, it must be wrapped
- * in a another non-text element.
- *
- * Example:
- * ```
- * <Translate>
- * Hello. Your score is <span><PlayerScore player={player} /></span>
- * </Translate>
- * ```
- */
-export class Translate extends React.Component<TranslateProps, {}> {
- render(): JSX.Element {
- const s = stringifyChildren(this.props.children);
- const translation: string = jed.ngettext(s, s, 1);
- const result = getTranslatedChildren(translation, this.props.children);
- if (!this.props.wrap) {
- return <div>{result}</div>;
- }
- return React.createElement(this.props.wrap, this.props.wrapProps, result);
- }
-}
-
-/**
- * Switch translation based on singular or plural based on the target prop.
- * Should only contain TranslateSingular and TransplatePlural as children.
- *
- * Example:
- * ```
- * <TranslateSwitch target={n}>
- * <TranslateSingular>I have {n} apple.</TranslateSingular>
- * <TranslatePlural>I have {n} apples.</TranslatePlural>
- * </TranslateSwitch>
- * ```
- */
-export class TranslateSwitch extends React.Component<
- TranslateSwitchProps,
- void
-> {
- render(): JSX.Element {
- let singular: React.ReactElement<TranslationPluralProps> | undefined;
- let plural: React.ReactElement<TranslationPluralProps> | undefined;
- const children = this.props.children;
- if (children) {
- React.Children.forEach(children, (child: any) => {
- if (child.type === TranslatePlural) {
- plural = child;
- }
- if (child.type === TranslateSingular) {
- singular = child;
- }
- });
- }
- if (!singular || !plural) {
- console.error("translation not found");
- return React.createElement("span", {}, ["translation not found"]);
- }
- singular.props.target = this.props.target;
- plural.props.target = this.props.target;
- // We're looking up the translation based on the
- // singular, even if we must use the plural form.
- return singular;
- }
-}
-
-interface TranslationPluralProps {
- target: number;
-}
-
-/**
- * See [[TranslateSwitch]].
- */
-export class TranslatePlural extends React.Component<
- TranslationPluralProps,
- void
-> {
- render(): JSX.Element {
- const s = stringifyChildren(this.props.children);
- const translation = jed.ngettext(s, s, 1);
- const result = getTranslatedChildren(translation, this.props.children);
- return <div>{result}</div>;
- }
-}
-
-/**
- * See [[TranslateSwitch]].
- */
-export class TranslateSingular extends React.Component<
- TranslationPluralProps,
- void
-> {
- render(): JSX.Element {
- const s = stringifyChildren(this.props.children);
- const translation = jed.ngettext(s, s, this.props.target);
- const result = getTranslatedChildren(translation, this.props.children);
- return <div>{result}</div>;
- }
-}
diff --git a/src/webex/pageEntryPoint.ts b/src/webex/pageEntryPoint.ts
deleted file mode 100644
index 9fd1d36f1..000000000
--- a/src/webex/pageEntryPoint.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2020 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/>
- */
-
-/**
- * Main entry point for extension pages.
- *
- * @author Florian Dold <dold@taler.net>
- */
-
-import ReactDOM from "react-dom";
-import { createPopup } from "./pages/popup";
-import { createWithdrawPage } from "./pages/withdraw";
-import { createWelcomePage } from "./pages/welcome";
-import { createPayPage } from "./pages/pay";
-import { createRefundPage } from "./pages/refund";
-
-function main(): void {
- try {
- let mainElement;
- const m = location.pathname.match(/([^/]+)$/);
- if (!m) {
- throw Error("can't parse page URL");
- }
- const page = m[1];
- switch (page) {
- case "popup.html":
- mainElement = createPopup();
- break;
- case "withdraw.html":
- mainElement = createWithdrawPage();
- break;
- case "welcome.html":
- mainElement = createWelcomePage();
- break;
- case "pay.html":
- mainElement = createPayPage();
- break;
- case "refund.html":
- mainElement = createRefundPage();
- break;
- default:
- throw Error(`page '${page}' not implemented`);
- }
- const container = document.getElementById("container");
- if (!container) {
- throw Error("container not found, can't mount page contents");
- }
- ReactDOM.render(mainElement, container);
- } catch (e) {
- console.error("got error", e);
- document.body.innerText = `Fatal error: "${e.message}". Please report this bug at https://bugs.gnunet.org/.`;
- }
-}
-
-if (document.readyState === "loading") {
- document.addEventListener("DOMContentLoaded", main);
-} else {
- main();
-}
diff --git a/src/webex/pages/add-auditor.tsx b/src/webex/pages/add-auditor.tsx
deleted file mode 100644
index c28d15cad..000000000
--- a/src/webex/pages/add-auditor.tsx
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- This file is part of TALER
- (C) 2017 Inria
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * View and edit auditors.
- *
- * @author Florian Dold
- */
-
-import { CurrencyRecord } from "../../types/dbTypes";
-import { getCurrencies, updateCurrency } from "../wxApi";
-import React, { useState } from "react";
-
-interface ConfirmAuditorProps {
- url: string;
- currency: string;
- auditorPub: string;
- expirationStamp: number;
-}
-
-function ConfirmAuditor(props: ConfirmAuditorProps): JSX.Element {
- const [addDone, setAddDone] = useState(false);
-
- const add = async (): Promise<void> => {
- const currencies = await getCurrencies();
- let currency: CurrencyRecord | undefined;
-
- for (const c of currencies) {
- if (c.name === props.currency) {
- currency = c;
- }
- }
-
- if (!currency) {
- currency = {
- name: props.currency,
- auditors: [],
- fractionalDigits: 2,
- exchanges: [],
- };
- }
-
- const newAuditor = {
- auditorPub: props.auditorPub,
- baseUrl: props.url,
- expirationStamp: props.expirationStamp,
- };
-
- let auditorFound = false;
- for (const idx in currency.auditors) {
- const a = currency.auditors[idx];
- if (a.baseUrl === props.url) {
- auditorFound = true;
- // Update auditor if already found by URL.
- currency.auditors[idx] = newAuditor;
- }
- }
-
- if (!auditorFound) {
- currency.auditors.push(newAuditor);
- }
-
- await updateCurrency(currency);
-
- setAddDone(true);
- };
-
- const back = (): void => {
- window.history.back();
- };
-
- return (
- <div id="main">
- <p>
- Do you want to let <strong>{props.auditorPub}</strong> audit the
- currency &quot;{props.currency}&quot;?
- </p>
- {addDone ? (
- <div>
- Auditor was added! You can also{" "}
- <a href={chrome.extension.getURL("/auditors.html")}>view and edit</a>{" "}
- auditors.
- </div>
- ) : (
- <div>
- <button
- onClick={() => add()}
- className="pure-button pure-button-primary"
- >
- Yes
- </button>
- <button onClick={() => back()} className="pure-button">
- No
- </button>
- </div>
- )}
- </div>
- );
-}
-
-export function makeAddAuditorPage(): JSX.Element {
- const walletPageUrl = new URL(document.location.href);
- const url = walletPageUrl.searchParams.get("url");
- if (!url) {
- throw Error("missign parameter (url)");
- }
- const currency = walletPageUrl.searchParams.get("currency");
- if (!currency) {
- throw Error("missing parameter (currency)");
- }
- const auditorPub = walletPageUrl.searchParams.get("auditorPub");
- if (!auditorPub) {
- throw Error("missing parameter (auditorPub)");
- }
- const auditorStampStr = walletPageUrl.searchParams.get("expirationStamp");
- if (!auditorStampStr) {
- throw Error("missing parameter (auditorStampStr)");
- }
- const expirationStamp = Number.parseInt(auditorStampStr);
- const args = { url, currency, auditorPub, expirationStamp };
- return <ConfirmAuditor {...args} />;
-}
diff --git a/src/webex/pages/auditors.tsx b/src/webex/pages/auditors.tsx
deleted file mode 100644
index ac93afd31..000000000
--- a/src/webex/pages/auditors.tsx
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- This file is part of TALER
- (C) 2017 Inria
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * View and edit auditors.
- *
- * @author Florian Dold
- */
-
-import {
- AuditorRecord,
- CurrencyRecord,
- ExchangeForCurrencyRecord,
-} from "../../types/dbTypes";
-
-import { getCurrencies, updateCurrency } from "../wxApi";
-
-import * as React from "react";
-
-interface CurrencyListState {
- currencies?: CurrencyRecord[];
-}
-
-class CurrencyList extends React.Component<{}, CurrencyListState> {
- constructor(props: {}) {
- super(props);
- const port = chrome.runtime.connect();
- port.onMessage.addListener((msg: any) => {
- if (msg.notify) {
- console.log("got notified");
- this.update();
- }
- });
- this.update();
- this.state = {} as any;
- }
-
- async update(): Promise<void> {
- const currencies = await getCurrencies();
- console.log("currencies: ", currencies);
- this.setState({ currencies });
- }
-
- async confirmRemoveAuditor(
- c: CurrencyRecord,
- a: AuditorRecord,
- ): Promise<void> {
- if (
- window.confirm(
- `Do you really want to remove auditor ${a.baseUrl} for currency ${c.name}?`,
- )
- ) {
- c.auditors = c.auditors.filter((x) => x.auditorPub !== a.auditorPub);
- await updateCurrency(c);
- }
- }
-
- async confirmRemoveExchange(
- c: CurrencyRecord,
- e: ExchangeForCurrencyRecord,
- ): Promise<void> {
- if (
- window.confirm(
- `Do you really want to remove exchange ${e.baseUrl} for currency ${c.name}?`,
- )
- ) {
- c.exchanges = c.exchanges.filter((x) => x.baseUrl !== e.baseUrl);
- await updateCurrency(c);
- }
- }
-
- renderAuditors(c: CurrencyRecord): any {
- if (c.auditors.length === 0) {
- return <p>No trusted auditors for this currency.</p>;
- }
- return (
- <div>
- <p>Trusted Auditors:</p>
- <ul>
- {c.auditors.map((a) => (
- <li key={a.baseUrl}>
- {a.baseUrl}{" "}
- <button
- className="pure-button button-destructive"
- onClick={() => this.confirmRemoveAuditor(c, a)}
- >
- Remove
- </button>
- <ul>
- <li>valid until {new Date(a.expirationStamp).toString()}</li>
- <li>public key {a.auditorPub}</li>
- </ul>
- </li>
- ))}
- </ul>
- </div>
- );
- }
-
- renderExchanges(c: CurrencyRecord): any {
- if (c.exchanges.length === 0) {
- return <p>No trusted exchanges for this currency.</p>;
- }
- return (
- <div>
- <p>Trusted Exchanges:</p>
- <ul>
- {c.exchanges.map((e) => (
- <li key={e.baseUrl}>
- {e.baseUrl}{" "}
- <button
- className="pure-button button-destructive"
- onClick={() => this.confirmRemoveExchange(c, e)}
- >
- Remove
- </button>
- </li>
- ))}
- </ul>
- </div>
- );
- }
-
- render(): JSX.Element {
- const currencies = this.state.currencies;
- if (!currencies) {
- return <span>...</span>;
- }
- return (
- <div id="main">
- {currencies.map((c) => (
- <div key={c.name}>
- <h1>Currency {c.name}</h1>
- <p>Displayed with {c.fractionalDigits} fractional digits.</p>
- <h2>Auditors</h2>
- <div>{this.renderAuditors(c)}</div>
- <h2>Exchanges</h2>
- <div>{this.renderExchanges(c)}</div>
- </div>
- ))}
- </div>
- );
- }
-}
-
-export function makeAuditorsPage(): JSX.Element {
- return <CurrencyList />;
-}
diff --git a/src/webex/pages/benchmark.tsx b/src/webex/pages/benchmark.tsx
deleted file mode 100644
index eb7193e0c..000000000
--- a/src/webex/pages/benchmark.tsx
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- This file is part of TALER
- (C) 2015 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Benchmarks for the wallet.
- *
- * @author Florian Dold
- */
-
-import * as i18n from "../i18n";
-
-import { BenchmarkResult } from "../../types/walletTypes";
-
-import * as wxApi from "../wxApi";
-
-import * as React from "react";
-
-interface BenchmarkRunnerState {
- repetitions: number;
- result?: BenchmarkResult;
- running: boolean;
-}
-
-function BenchmarkDisplay(props: BenchmarkRunnerState): JSX.Element {
- const result = props.result;
- if (!result) {
- if (props.running) {
- return <div>Waiting for results ...</div>;
- } else {
- return <div></div>;
- }
- }
- return (
- <>
- <h2>Results for {result.repetitions} repetitions</h2>
- <table className="pure-table">
- <thead>
- <tr>
- <th>{i18n.str`Operation`}</th>
- <th>{i18n.str`time (ms/op)`}</th>
- </tr>
- {Object.keys(result.time)
- .sort()
- .map((k) => (
- <tr key={k}>
- <td>{k}</td>
- <td>{result.time[k] / result.repetitions}</td>
- </tr>
- ))}
- </thead>
- </table>
- </>
- );
-}
-
-class BenchmarkRunner extends React.Component<any, BenchmarkRunnerState> {
- constructor(props: any) {
- super(props);
- this.state = {
- repetitions: 10,
- running: false,
- };
- }
-
- async run(): Promise<void> {
- this.setState({ result: undefined, running: true });
- const result = await wxApi.benchmarkCrypto(this.state.repetitions);
- this.setState({ result, running: false });
- }
-
- render(): JSX.Element {
- return (
- <div>
- <label>Repetitions:</label>
- <input
- type="number"
- value={this.state.repetitions}
- onChange={(evt) =>
- this.setState({ repetitions: Number.parseInt(evt.target.value) })
- }
- />{" "}
- <button onClick={() => this.run()}>Run</button>
- <BenchmarkDisplay {...this.state} />
- </div>
- );
- }
-}
-
-export function makeBenchmarkPage(): JSX.Element {
- return <BenchmarkRunner />;
-}
diff --git a/src/webex/pages/pay.tsx b/src/webex/pages/pay.tsx
deleted file mode 100644
index ce44c0040..000000000
--- a/src/webex/pages/pay.tsx
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- This file is part of TALER
- (C) 2015 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Page shown to the user to confirm entering
- * a contract.
- */
-
-/**
- * Imports.
- */
-import * as i18n from "../i18n";
-
-import { PreparePayResult, PreparePayResultType } from "../../types/walletTypes";
-
-import { renderAmount, ProgressButton } from "../renderHtml";
-import * as wxApi from "../wxApi";
-
-import React, { useState, useEffect } from "react";
-
-import * as Amounts from "../../util/amounts";
-import { codecForContractTerms, ContractTerms } from "../../types/talerTypes";
-
-function TalerPayDialog({ talerPayUri }: { talerPayUri: string }): JSX.Element {
- const [payStatus, setPayStatus] = useState<PreparePayResult | undefined>();
- const [payErrMsg, setPayErrMsg] = useState<string | undefined>("");
- const [numTries, setNumTries] = useState(0);
- const [loading, setLoading] = useState(false);
- let amountEffective: Amounts.AmountJson | undefined = undefined;
-
- useEffect(() => {
- const doFetch = async (): Promise<void> => {
- const p = await wxApi.preparePay(talerPayUri);
- setPayStatus(p);
- };
- doFetch();
- }, [numTries, talerPayUri]);
-
- if (!payStatus) {
- return <span>Loading payment information ...</span>;
- }
-
- let insufficientBalance = false;
- if (payStatus.status == "insufficient-balance") {
- insufficientBalance = true;
- }
-
- if (payStatus.status === "payment-possible") {
- amountEffective = Amounts.parseOrThrow(payStatus.amountEffective);
- }
-
- if (payStatus.status === PreparePayResultType.AlreadyConfirmed && numTries === 0) {
- return (
- <span>
- You have already paid for this article. Click{" "}
- <a href={payStatus.nextUrl}>here</a> to view it again.
- </span>
- );
- }
-
- let contractTerms: ContractTerms;
-
- try {
- contractTerms = codecForContractTerms().decode(payStatus.contractTerms);
- } catch (e) {
- // This should never happen, as the wallet is supposed to check the contract terms
- // before storing them.
- console.error(e);
- console.log("raw contract terms were", payStatus.contractTerms);
- return <span>Invalid contract terms.</span>;
- }
-
- if (!contractTerms) {
- return (
- <span>
- Error: did not get contract terms from merchant or wallet backend.
- </span>
- );
- }
-
- let merchantName: React.ReactElement;
- if (contractTerms.merchant && contractTerms.merchant.name) {
- merchantName = <strong>{contractTerms.merchant.name}</strong>;
- } else {
- merchantName = <strong>(pub: {contractTerms.merchant_pub})</strong>;
- }
-
- const amount = (
- <strong>{renderAmount(Amounts.parseOrThrow(contractTerms.amount))}</strong>
- );
-
- const doPayment = async (): Promise<void> => {
- if (payStatus.status !== "payment-possible") {
- throw Error(`invalid state: ${payStatus.status}`);
- }
- const proposalId = payStatus.proposalId;
- setNumTries(numTries + 1);
- try {
- setLoading(true);
- const res = await wxApi.confirmPay(proposalId, undefined);
- document.location.href = res.nextUrl;
- } catch (e) {
- console.error(e);
- setPayErrMsg(e.message);
- }
- };
-
- return (
- <div>
- <p>
- <i18n.Translate wrap="p">
- The merchant <span>{merchantName}</span> offers you to purchase:
- </i18n.Translate>
- <div style={{ textAlign: "center" }}>
- <strong>{contractTerms.summary}</strong>
- </div>
- {amountEffective ? (
- <i18n.Translate wrap="p">
- The total price is <span>{amount} </span>
- (plus <span>{renderAmount(amountEffective)}</span> fees).
- </i18n.Translate>
- ) : (
- <i18n.Translate wrap="p">
- The total price is <span>{amount}</span>.
- </i18n.Translate>
- )}
- </p>
-
- {insufficientBalance ? (
- <div>
- <p style={{ color: "red", fontWeight: "bold" }}>
- Unable to pay: Your balance is insufficient.
- </p>
- </div>
- ) : null}
-
- {payErrMsg ? (
- <div>
- <p>Payment failed: {payErrMsg}</p>
- <button
- className="pure-button button-success"
- onClick={() => doPayment()}
- >
- {i18n.str`Retry`}
- </button>
- </div>
- ) : (
- <div>
- <ProgressButton
- loading={loading}
- disabled={insufficientBalance}
- onClick={() => doPayment()}
- >
- {i18n.str`Confirm payment`}
- </ProgressButton>
- </div>
- )}
- </div>
- );
-}
-
-export function createPayPage(): JSX.Element {
- const url = new URL(document.location.href);
- const talerPayUri = url.searchParams.get("talerPayUri");
- if (!talerPayUri) {
- throw Error("invalid parameter");
- }
- return <TalerPayDialog talerPayUri={talerPayUri} />;
-}
diff --git a/src/webex/pages/payback.tsx b/src/webex/pages/payback.tsx
deleted file mode 100644
index 5d42f5f47..000000000
--- a/src/webex/pages/payback.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- This file is part of TALER
- (C) 2017 Inria
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * View and edit auditors.
- *
- * @author Florian Dold
- */
-
-/**
- * Imports.
- */
-import * as React from "react";
-
-export function makePaybackPage(): JSX.Element {
- return <div>not implemented</div>;
-}
diff --git a/src/webex/pages/popup.tsx b/src/webex/pages/popup.tsx
deleted file mode 100644
index 8a99a6d90..000000000
--- a/src/webex/pages/popup.tsx
+++ /dev/null
@@ -1,499 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Popup shown to the user when they click
- * the Taler browser action button.
- *
- * @author Florian Dold
- */
-
-/**
- * Imports.
- */
-import * as i18n from "../i18n";
-
-import { AmountJson } from "../../util/amounts";
-import * as Amounts from "../../util/amounts";
-
-import { abbrev, renderAmount, PageLink } from "../renderHtml";
-import * as wxApi from "../wxApi";
-
-import React, { Fragment, useState, useEffect } from "react";
-
-import moment from "moment";
-import { Timestamp } from "../../util/time";
-import { classifyTalerUri, TalerUriType } from "../../util/taleruri";
-import { PermissionsCheckbox } from "./welcome";
-import { BalancesResponse, Balance } from "../../types/walletTypes";
-
-// FIXME: move to newer react functions
-/* eslint-disable react/no-deprecated */
-
-class Router extends React.Component<any, any> {
- static setRoute(s: string): void {
- window.location.hash = s;
- }
-
- static getRoute(): string {
- // Omit the '#' at the beginning
- return window.location.hash.substring(1);
- }
-
- static onRoute(f: any): () => void {
- Router.routeHandlers.push(f);
- return () => {
- const i = Router.routeHandlers.indexOf(f);
- this.routeHandlers = this.routeHandlers.splice(i, 1);
- };
- }
-
- private static routeHandlers: any[] = [];
-
- componentWillMount(): void {
- console.log("router mounted");
- window.onhashchange = () => {
- this.setState({});
- for (const f of Router.routeHandlers) {
- f();
- }
- };
- }
-
- render(): JSX.Element {
- const route = window.location.hash.substring(1);
- console.log("rendering route", route);
- let defaultChild: React.ReactChild | null = null;
- let foundChild: React.ReactChild | null = null;
- React.Children.forEach(this.props.children, (child) => {
- const childProps: any = (child as any).props;
- if (!childProps) {
- return;
- }
- if (childProps.default) {
- defaultChild = child as React.ReactChild;
- }
- if (childProps.route === route) {
- foundChild = child as React.ReactChild;
- }
- });
- const c: React.ReactChild | null = foundChild || defaultChild;
- if (!c) {
- throw Error("unknown route");
- }
- Router.setRoute((c as any).props.route);
- return <div>{c}</div>;
- }
-}
-
-interface TabProps {
- target: string;
- children?: React.ReactNode;
-}
-
-function Tab(props: TabProps): JSX.Element {
- let cssClass = "";
- if (props.target === Router.getRoute()) {
- cssClass = "active";
- }
- const onClick = (e: React.MouseEvent<HTMLAnchorElement>): void => {
- Router.setRoute(props.target);
- e.preventDefault();
- };
- return (
- <a onClick={onClick} href={props.target} className={cssClass}>
- {props.children}
- </a>
- );
-}
-
-class WalletNavBar extends React.Component<any, any> {
- private cancelSubscription: any;
-
- componentWillMount(): void {
- this.cancelSubscription = Router.onRoute(() => {
- this.setState({});
- });
- }
-
- componentWillUnmount(): void {
- if (this.cancelSubscription) {
- this.cancelSubscription();
- }
- }
-
- render(): JSX.Element {
- console.log("rendering nav bar");
- return (
- <div className="nav" id="header">
- <Tab target="/balance">{i18n.str`Balance`}</Tab>
- <Tab target="/history">{i18n.str`History`}</Tab>
- <Tab target="/settings">{i18n.str`Settings`}</Tab>
- <Tab target="/debug">{i18n.str`Debug`}</Tab>
- </div>
- );
- }
-}
-
-/**
- * Render an amount as a large number with a small currency symbol.
- */
-function bigAmount(amount: AmountJson): JSX.Element {
- const v = amount.value + amount.fraction / Amounts.fractionalBase;
- return (
- <span>
- <span style={{ fontSize: "5em", display: "block" }}>{v}</span>{" "}
- <span>{amount.currency}</span>
- </span>
- );
-}
-
-function EmptyBalanceView(): JSX.Element {
- return (
- <i18n.Translate wrap="p">
- You have no balance to show. Need some{" "}
- <PageLink pageName="welcome.html">help</PageLink> getting started?
- </i18n.Translate>
- );
-}
-
-class WalletBalanceView extends React.Component<any, any> {
- private balance: BalancesResponse;
- private gotError = false;
- private canceler: (() => void) | undefined = undefined;
- private unmount = false;
- private updateBalanceRunning = false;
-
- componentWillMount(): void {
- this.canceler = wxApi.onUpdateNotification(() => this.updateBalance());
- this.updateBalance();
- }
-
- componentWillUnmount(): void {
- console.log("component WalletBalanceView will unmount");
- if (this.canceler) {
- this.canceler();
- }
- this.unmount = true;
- }
-
- async updateBalance(): Promise<void> {
- if (this.updateBalanceRunning) {
- return;
- }
- this.updateBalanceRunning = true;
- let balance: BalancesResponse;
- try {
- balance = await wxApi.getBalance();
- } catch (e) {
- if (this.unmount) {
- return;
- }
- this.gotError = true;
- console.error("could not retrieve balances", e);
- this.setState({});
- return;
- } finally {
- this.updateBalanceRunning = false;
- }
- if (this.unmount) {
- return;
- }
- this.gotError = false;
- console.log("got balance", balance);
- this.balance = balance;
- this.setState({});
- }
-
- formatPending(entry: Balance): JSX.Element {
- let incoming: JSX.Element | undefined;
- let payment: JSX.Element | undefined;
-
- const available = Amounts.parseOrThrow(entry.available);
- const pendingIncoming = Amounts.parseOrThrow(entry.pendingIncoming);
- const pendingOutgoing = Amounts.parseOrThrow(entry.pendingOutgoing);
-
- console.log(
- "available: ",
- entry.pendingIncoming ? renderAmount(entry.available) : null,
- );
- console.log(
- "incoming: ",
- entry.pendingIncoming ? renderAmount(entry.pendingIncoming) : null,
- );
-
- if (Amounts.isNonZero(pendingIncoming)) {
- incoming = (
- <i18n.Translate wrap="span">
- <span style={{ color: "darkgreen" }}>
- {"+"}
- {renderAmount(entry.pendingIncoming)}
- </span>{" "}
- incoming
- </i18n.Translate>
- );
- }
-
- const l = [incoming, payment].filter((x) => x !== undefined);
- if (l.length === 0) {
- return <span />;
- }
-
- if (l.length === 1) {
- return <span>({l})</span>;
- }
- return (
- <span>
- ({l[0]}, {l[1]})
- </span>
- );
- }
-
- render(): JSX.Element {
- const wallet = this.balance;
- if (this.gotError) {
- return (
- <div className="balance">
- <p>{i18n.str`Error: could not retrieve balance information.`}</p>
- <p>
- Click <PageLink pageName="welcome.html">here</PageLink> for help and
- diagnostics.
- </p>
- </div>
- );
- }
- if (!wallet) {
- return <span></span>;
- }
- console.log(wallet);
- const listing = wallet.balances.map((entry) => {
- const av = Amounts.parseOrThrow(entry.available);
- return (
- <p key={av.currency}>
- {bigAmount(av)} {this.formatPending(entry)}
- </p>
- );
- });
- return listing.length > 0 ? (
- <div className="balance">{listing}</div>
- ) : (
- <EmptyBalanceView />
- );
- }
-}
-
-function Icon({ l }: { l: string }): JSX.Element {
- return <div className={"icon"}>{l}</div>;
-}
-
-function formatAndCapitalize(text: string): string {
- text = text.replace("-", " ");
- text = text.replace(/^./, text[0].toUpperCase());
- return text;
-}
-
-const HistoryComponent = (props: any): JSX.Element => {
- return <span>TBD</span>;
-};
-
-class WalletSettings extends React.Component<any, any> {
- render(): JSX.Element {
- return (
- <div>
- <h2>Permissions</h2>
- <PermissionsCheckbox />
- </div>
- );
- }
-}
-
-function reload(): void {
- try {
- chrome.runtime.reload();
- window.close();
- } catch (e) {
- // Functionality missing in firefox, ignore!
- }
-}
-
-function confirmReset(): void {
- if (
- confirm(
- "Do you want to IRREVOCABLY DESTROY everything inside your" +
- " wallet and LOSE ALL YOUR COINS?",
- )
- ) {
- wxApi.resetDb();
- window.close();
- }
-}
-
-function WalletDebug(props: any): JSX.Element {
- return (
- <div>
- <p>Debug tools:</p>
- <button onClick={openExtensionPage("/popup.html")}>wallet tab</button>
- <button onClick={openExtensionPage("/benchmark.html")}>benchmark</button>
- <button onClick={openExtensionPage("/show-db.html")}>show db</button>
- <button onClick={openExtensionPage("/tree.html")}>show tree</button>
- <br />
- <button onClick={confirmReset}>reset</button>
- <button onClick={reload}>reload chrome extension</button>
- </div>
- );
-}
-
-function openExtensionPage(page: string) {
- return () => {
- chrome.tabs.create({
- url: chrome.extension.getURL(page),
- });
- };
-}
-
-function openTab(page: string) {
- return (evt: React.SyntheticEvent<any>) => {
- evt.preventDefault();
- chrome.tabs.create({
- url: page,
- });
- };
-}
-
-function makeExtensionUrlWithParams(
- url: string,
- params?: { [name: string]: string | undefined },
-): string {
- const innerUrl = new URL(chrome.extension.getURL("/" + url));
- if (params) {
- for (const key in params) {
- const p = params[key];
- if (p) {
- innerUrl.searchParams.set(key, p);
- }
- }
- }
- return innerUrl.href;
-}
-
-function actionForTalerUri(talerUri: string): string | undefined {
- const uriType = classifyTalerUri(talerUri);
- switch (uriType) {
- case TalerUriType.TalerWithdraw:
- return makeExtensionUrlWithParams("withdraw.html", {
- talerWithdrawUri: talerUri,
- });
- case TalerUriType.TalerPay:
- return makeExtensionUrlWithParams("pay.html", {
- talerPayUri: talerUri,
- });
- case TalerUriType.TalerTip:
- return makeExtensionUrlWithParams("tip.html", {
- talerTipUri: talerUri,
- });
- case TalerUriType.TalerRefund:
- return makeExtensionUrlWithParams("refund.html", {
- talerRefundUri: talerUri,
- });
- case TalerUriType.TalerNotifyReserve:
- // FIXME: implement
- break;
- default:
- console.warn(
- "Response with HTTP 402 has Taler header, but header value is not a taler:// URI.",
- );
- break;
- }
- return undefined;
-}
-
-async function findTalerUriInActiveTab(): Promise<string | undefined> {
- return new Promise((resolve, reject) => {
- chrome.tabs.executeScript(
- {
- code: `
- (() => {
- let x = document.querySelector("a[href^='taler://'");
- return x ? x.href.toString() : null;
- })();
- `,
- allFrames: false,
- },
- (result) => {
- if (chrome.runtime.lastError) {
- console.error(chrome.runtime.lastError);
- resolve(undefined);
- return;
- }
- console.log("got result", result);
- resolve(result[0]);
- },
- );
- });
-}
-
-function WalletPopup(): JSX.Element {
- const [talerActionUrl, setTalerActionUrl] = useState<string | undefined>(
- undefined,
- );
- const [dismissed, setDismissed] = useState(false);
- useEffect(() => {
- async function check(): Promise<void> {
- const talerUri = await findTalerUriInActiveTab();
- if (talerUri) {
- const actionUrl = actionForTalerUri(talerUri);
- setTalerActionUrl(actionUrl);
- }
- }
- check();
- });
- if (talerActionUrl && !dismissed) {
- return (
- <div style={{ padding: "1em" }}>
- <h1>Taler Action</h1>
- <p>This page has a Taler action. </p>
- <p>
- <button
- onClick={() => {
- window.open(talerActionUrl, "_blank");
- }}
- >
- Open
- </button>
- </p>
- <p>
- <button onClick={() => setDismissed(true)}>Dismiss</button>
- </p>
- </div>
- );
- }
- return (
- <div>
- <WalletNavBar />
- <div style={{ margin: "1em" }}>
- <Router>
- <WalletBalanceView route="/balance" default />
- <WalletSettings route="/settings" />
- <WalletDebug route="/debug" />
- </Router>
- </div>
- </div>
- );
-}
-
-export function createPopup(): JSX.Element {
- return <WalletPopup />;
-}
diff --git a/src/webex/pages/refund.tsx b/src/webex/pages/refund.tsx
deleted file mode 100644
index c5d6a00df..000000000
--- a/src/webex/pages/refund.tsx
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- This file is part of TALER
- (C) 2015-2016 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Page that shows refund status for purchases.
- *
- * @author Florian Dold
- */
-
-import React, { useEffect, useState } from "react";
-
-import * as wxApi from "../wxApi";
-import { PurchaseDetails } from "../../types/walletTypes";
-import { AmountView } from "../renderHtml";
-
-function RefundStatusView(props: { talerRefundUri: string }): JSX.Element {
- const [applied, setApplied] = useState(false);
- const [purchaseDetails, setPurchaseDetails] = useState<
- PurchaseDetails | undefined
- >(undefined);
- const [errMsg, setErrMsg] = useState<string | undefined>(undefined);
-
- useEffect(() => {
- const doFetch = async (): Promise<void> => {
- try {
- const result = await wxApi.applyRefund(props.talerRefundUri);
- setApplied(true);
- const r = await wxApi.getPurchaseDetails(result.proposalId);
- setPurchaseDetails(r);
- } catch (e) {
- console.error(e);
- setErrMsg(e.message);
- console.log("err message", e.message);
- }
- };
- doFetch();
- }, [props.talerRefundUri]);
-
- console.log("rendering");
-
- if (errMsg) {
- return <span>Error: {errMsg}</span>;
- }
-
- if (!applied || !purchaseDetails) {
- return <span>Updating refund status</span>;
- }
-
- return (
- <>
- <h2>Refund Status</h2>
- <p>
- The product <em>{purchaseDetails.contractTerms.summary}</em> has
- received a total refund of{" "}
- <AmountView amount={purchaseDetails.totalRefundAmount} />.
- </p>
- <p>Note that additional fees from the exchange may apply.</p>
- </>
- );
-}
-
-export function createRefundPage(): JSX.Element {
- const url = new URL(document.location.href);
-
- const container = document.getElementById("container");
- if (!container) {
- throw Error("fatal: can't mount component, container missing");
- }
-
- const talerRefundUri = url.searchParams.get("talerRefundUri");
- if (!talerRefundUri) {
- throw Error("taler refund URI requred");
- }
-
- return <RefundStatusView talerRefundUri={talerRefundUri} />;
-}
diff --git a/src/webex/pages/reset-required.tsx b/src/webex/pages/reset-required.tsx
deleted file mode 100644
index 9e40e7981..000000000
--- a/src/webex/pages/reset-required.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- This file is part of TALER
- (C) 2017 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Page to inform the user when a database reset is required.
- *
- * @author Florian Dold
- */
-
-import * as React from "react";
-
-import * as wxApi from "../wxApi";
-
-class State {
- /**
- * Did the user check the confirmation check box?
- */
- checked: boolean;
-
- /**
- * Do we actually need to reset the db?
- */
- resetRequired: boolean;
-}
-
-class ResetNotification extends React.Component<any, State> {
- constructor(props: any) {
- super(props);
- this.state = { checked: false, resetRequired: true };
- setInterval(() => this.update(), 500);
- }
- async update(): Promise<void> {
- const res = await wxApi.checkUpgrade();
- this.setState({ resetRequired: res.dbResetRequired });
- }
- render(): JSX.Element {
- if (this.state.resetRequired) {
- return (
- <div>
- <h1>Manual Reset Reqired</h1>
- <p>
- The wallet&apos;s database in your browser is incompatible with the{" "}
- currently installed wallet. Please reset manually.
- </p>
- <p>
- Once the database format has stabilized, we will provide automatic
- upgrades.
- </p>
- <input
- id="check"
- type="checkbox"
- checked={this.state.checked}
- onChange={(e) => this.setState({ checked: e.target.checked })}
- />{" "}
- <label htmlFor="check">
- I understand that I will lose all my data
- </label>
- <br />
- <button
- className="pure-button"
- disabled={!this.state.checked}
- onClick={() => wxApi.resetDb()}
- >
- Reset
- </button>
- </div>
- );
- }
- return (
- <div>
- <h1>Everything is fine!</h1>A reset is not required anymore, you can
- close this page.
- </div>
- );
- }
-}
-
-export function createResetRequiredPage(): JSX.Element {
- return <ResetNotification />;
-}
diff --git a/src/webex/pages/return-coins.tsx b/src/webex/pages/return-coins.tsx
deleted file mode 100644
index e8cf8c9dd..000000000
--- a/src/webex/pages/return-coins.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- This file is part of TALER
- (C) 2017 Inria
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Return coins to own bank account.
- *
- * @author Florian Dold
- */
-
-/**
- * Imports.
- */
-import * as React from "react";
-
-export function createReturnCoinsPage(): JSX.Element {
- return <span>Not implemented yet.</span>;
-}
diff --git a/src/webex/pages/tip.tsx b/src/webex/pages/tip.tsx
deleted file mode 100644
index 4a1d3743a..000000000
--- a/src/webex/pages/tip.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- This file is part of TALER
- (C) 2017 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Page shown to the user to confirm creation
- * of a reserve, usually requested by the bank.
- *
- * @author Florian Dold
- */
-
-import * as React from "react";
-
-import { acceptTip, getTipStatus } from "../wxApi";
-
-import { renderAmount, ProgressButton } from "../renderHtml";
-
-import { useState, useEffect } from "react";
-import { TipStatus } from "../../types/walletTypes";
-
-function TipDisplay(props: { talerTipUri: string }): JSX.Element {
- const [tipStatus, setTipStatus] = useState<TipStatus | undefined>(undefined);
- const [discarded, setDiscarded] = useState(false);
- const [loading, setLoading] = useState(false);
- const [finished, setFinished] = useState(false);
-
- useEffect(() => {
- const doFetch = async (): Promise<void> => {
- const ts = await getTipStatus(props.talerTipUri);
- setTipStatus(ts);
- };
- doFetch();
- }, [props.talerTipUri]);
-
- if (discarded) {
- return <span>You&apos;ve discarded the tip.</span>;
- }
-
- if (finished) {
- return <span>Tip has been accepted!</span>;
- }
-
- if (!tipStatus) {
- return <span>Loading ...</span>;
- }
-
- const discard = (): void => {
- setDiscarded(true);
- };
-
- const accept = async (): Promise<void> => {
- setLoading(true);
- await acceptTip(tipStatus.tipId);
- setFinished(true);
- };
-
- return (
- <div>
- <h2>Tip Received!</h2>
- <p>
- You received a tip of <strong>{renderAmount(tipStatus.amount)}</strong>{" "}
- from <span> </span>
- <strong>{tipStatus.merchantOrigin}</strong>.
- </p>
- <p>
- The tip is handled by the exchange{" "}
- <strong>{tipStatus.exchangeUrl}</strong>. This exchange will charge fees
- of <strong>{renderAmount(tipStatus.totalFees)}</strong> for this
- operation.
- </p>
- <form className="pure-form">
- <ProgressButton loading={loading} onClick={() => accept()}>
- Accept Tip
- </ProgressButton>{" "}
- <button className="pure-button" type="button" onClick={() => discard()}>
- Discard tip
- </button>
- </form>
- </div>
- );
-}
-
-export function createTipPage(): JSX.Element {
- const url = new URL(document.location.href);
- const talerTipUri = url.searchParams.get("talerTipUri");
- if (typeof talerTipUri !== "string") {
- throw Error("talerTipUri must be a string");
- }
-
- return <TipDisplay talerTipUri={talerTipUri} />;
-}
diff --git a/src/webex/pages/welcome.tsx b/src/webex/pages/welcome.tsx
deleted file mode 100644
index a7c24d659..000000000
--- a/src/webex/pages/welcome.tsx
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2019 Taler Systems SA
-
- 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/>
- */
-
-/**
- * Welcome page, shown on first installs.
- *
- * @author Florian Dold
- */
-
-import React, { useState, useEffect } from "react";
-import { getDiagnostics } from "../wxApi";
-import { PageLink } from "../renderHtml";
-import { WalletDiagnostics } from "../../types/walletTypes";
-import * as wxApi from "../wxApi";
-import { getPermissionsApi } from "../compat";
-import { extendedPermissions } from "../permissions";
-
-function Diagnostics(): JSX.Element | null {
- const [timedOut, setTimedOut] = useState(false);
- const [diagnostics, setDiagnostics] = useState<WalletDiagnostics | undefined>(
- undefined,
- );
-
- useEffect(() => {
- let gotDiagnostics = false;
- setTimeout(() => {
- if (!gotDiagnostics) {
- console.error("timed out");
- setTimedOut(true);
- }
- }, 1000);
- const doFetch = async (): Promise<void> => {
- const d = await getDiagnostics();
- console.log("got diagnostics", d);
- gotDiagnostics = true;
- setDiagnostics(d);
- };
- console.log("fetching diagnostics");
- doFetch();
- }, []);
-
- if (timedOut) {
- return <p>Diagnostics timed out. Could not talk to the wallet backend.</p>;
- }
-
- if (diagnostics) {
- if (diagnostics.errors.length === 0) {
- return null;
- } else {
- return (
- <div
- style={{
- borderLeft: "0.5em solid red",
- paddingLeft: "1em",
- paddingTop: "0.2em",
- paddingBottom: "0.2em",
- }}
- >
- <p>Problems detected:</p>
- <ol>
- {diagnostics.errors.map((errMsg) => (
- <li key={errMsg}>{errMsg}</li>
- ))}
- </ol>
- {diagnostics.firefoxIdbProblem ? (
- <p>
- Please check in your <code>about:config</code> settings that you
- have IndexedDB enabled (check the preference name{" "}
- <code>dom.indexedDB.enabled</code>).
- </p>
- ) : null}
- {diagnostics.dbOutdated ? (
- <p>
- Your wallet database is outdated. Currently automatic migration is
- not supported. Please go{" "}
- <PageLink pageName="reset-required.html">here</PageLink> to reset
- the wallet database.
- </p>
- ) : null}
- </div>
- );
- }
- }
-
- return <p>Running diagnostics ...</p>;
-}
-
-export function PermissionsCheckbox(): JSX.Element {
- const [extendedPermissionsEnabled, setExtendedPermissionsEnabled] = useState(
- false,
- );
- async function handleExtendedPerm(requestedVal: boolean): Promise<void> {
- let nextVal: boolean | undefined;
- if (requestedVal) {
- const granted = await new Promise<boolean>((resolve, reject) => {
- // We set permissions here, since apparently FF wants this to be done
- // as the result of an input event ...
- getPermissionsApi().request(extendedPermissions, (granted: boolean) => {
- if (chrome.runtime.lastError) {
- console.error("error requesting permissions");
- console.error(chrome.runtime.lastError);
- reject(chrome.runtime.lastError);
- return;
- }
- console.log("permissions granted:", granted);
- resolve(granted);
- });
- });
- const res = await wxApi.setExtendedPermissions(granted);
- console.log(res);
- nextVal = res.newValue;
- } else {
- const res = await wxApi.setExtendedPermissions(false);
- console.log(res);
- nextVal = res.newValue;
- }
- console.log("new permissions applied:", nextVal);
- setExtendedPermissionsEnabled(nextVal ?? false);
- }
- useEffect(() => {
- async function getExtendedPermValue(): Promise<void> {
- const res = await wxApi.getExtendedPermissions();
- setExtendedPermissionsEnabled(res.newValue);
- }
- getExtendedPermValue();
- });
- return (
- <div>
- <input
- checked={extendedPermissionsEnabled}
- onChange={(x) => handleExtendedPerm(x.target.checked)}
- type="checkbox"
- id="checkbox-perm"
- style={{ width: "1.5em", height: "1.5em", verticalAlign: "middle" }}
- />
- <label
- htmlFor="checkbox-perm"
- style={{ marginLeft: "0.5em", fontWeight: "bold" }}
- >
- Automatically open wallet based on page content
- </label>
- <span
- style={{
- color: "#383838",
- fontSize: "smaller",
- display: "block",
- marginLeft: "2em",
- }}
- >
- (Enabling this option below will make using the wallet faster, but
- requires more permissions from your browser.)
- </span>
- </div>
- );
-}
-
-function Welcome(): JSX.Element {
- return (
- <>
- <p>Thank you for installing the wallet.</p>
- <Diagnostics />
- <h2>Permissions</h2>
- <PermissionsCheckbox />
- <h2>Next Steps</h2>
- <a href="https://demo.taler.net/" style={{ display: "block" }}>
- Try the demo »
- </a>
- <a href="https://demo.taler.net/" style={{ display: "block" }}>
- Learn how to top up your wallet balance »
- </a>
- </>
- );
-}
-
-export function createWelcomePage(): JSX.Element {
- return <Welcome />;
-}
diff --git a/src/webex/pages/withdraw.tsx b/src/webex/pages/withdraw.tsx
deleted file mode 100644
index 4a92704b3..000000000
--- a/src/webex/pages/withdraw.tsx
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- This file is part of TALER
- (C) 2015-2016 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Page shown to the user to confirm creation
- * of a reserve, usually requested by the bank.
- *
- * @author Florian Dold
- */
-
-import * as i18n from "../i18n";
-
-import { WithdrawDetailView, renderAmount } from "../renderHtml";
-
-import React, { useState, useEffect } from "react";
-import {
- acceptWithdrawal,
- onUpdateNotification,
-} from "../wxApi";
-
-function WithdrawalDialog(props: { talerWithdrawUri: string }): JSX.Element {
- const [details, setDetails] = useState<
- any | undefined
- >();
- const [selectedExchange, setSelectedExchange] = useState<
- string | undefined
- >();
- const talerWithdrawUri = props.talerWithdrawUri;
- const [cancelled, setCancelled] = useState(false);
- const [selecting, setSelecting] = useState(false);
- const [customUrl, setCustomUrl] = useState<string>("");
- const [errMsg, setErrMsg] = useState<string | undefined>("");
- const [updateCounter, setUpdateCounter] = useState(1);
-
- useEffect(() => {
- return onUpdateNotification(() => {
- setUpdateCounter(updateCounter + 1);
- });
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- useEffect(() => {
- const fetchData = async (): Promise<void> => {
- // FIXME: re-implement with new API
- // console.log("getting from", talerWithdrawUri);
- // let d: WithdrawalDetailsResponse | undefined = undefined;
- // try {
- // d = await getWithdrawDetails(talerWithdrawUri, selectedExchange);
- // } catch (e) {
- // console.error(
- // `error getting withdraw details for uri ${talerWithdrawUri}, exchange ${selectedExchange}`,
- // e,
- // );
- // setErrMsg(e.message);
- // return;
- // }
- // console.log("got withdrawDetails", d);
- // if (!selectedExchange && d.bankWithdrawDetails.suggestedExchange) {
- // console.log("setting selected exchange");
- // setSelectedExchange(d.bankWithdrawDetails.suggestedExchange);
- // }
- // setDetails(d);
- };
- fetchData();
- }, [selectedExchange, errMsg, selecting, talerWithdrawUri, updateCounter]);
-
- if (errMsg) {
- return (
- <div>
- <i18n.Translate wrap="p">
- Could not get details for withdraw operation:
- </i18n.Translate>
- <p style={{ color: "red" }}>{errMsg}</p>
- <p>
- <span
- role="button"
- tabIndex={0}
- style={{ textDecoration: "underline", cursor: "pointer" }}
- onClick={() => {
- setSelecting(true);
- setErrMsg(undefined);
- setSelectedExchange(undefined);
- setDetails(undefined);
- }}
- >
- {i18n.str`Chose different exchange provider`}
- </span>
- </p>
- </div>
- );
- }
-
- if (!details) {
- return <span>Loading...</span>;
- }
-
- if (cancelled) {
- return <span>Withdraw operation has been cancelled.</span>;
- }
-
- if (selecting) {
- const bankSuggestion =
- details && details.bankWithdrawDetails.suggestedExchange;
- return (
- <div>
- {i18n.str`Please select an exchange. You can review the details before after your selection.`}
- {bankSuggestion && (
- <div>
- <h2>Bank Suggestion</h2>
- <button
- className="pure-button button-success"
- onClick={() => {
- setDetails(undefined);
- setSelectedExchange(bankSuggestion);
- setSelecting(false);
- }}
- >
- <i18n.Translate wrap="span">
- Select <strong>{bankSuggestion}</strong>
- </i18n.Translate>
- </button>
- </div>
- )}
- <h2>Custom Selection</h2>
- <p>
- <input
- type="text"
- onChange={(e) => setCustomUrl(e.target.value)}
- value={customUrl}
- />
- </p>
- <button
- className="pure-button button-success"
- onClick={() => {
- setDetails(undefined);
- setSelectedExchange(customUrl);
- setSelecting(false);
- }}
- >
- <i18n.Translate wrap="span">Select custom exchange</i18n.Translate>
- </button>
- </div>
- );
- }
-
- const accept = async (): Promise<void> => {
- if (!selectedExchange) {
- throw Error("can't accept, no exchange selected");
- }
- console.log("accepting exchange", selectedExchange);
- const res = await acceptWithdrawal(talerWithdrawUri, selectedExchange);
- console.log("accept withdrawal response", res);
- if (res.confirmTransferUrl) {
- document.location.href = res.confirmTransferUrl;
- }
- };
-
- return (
- <div>
- <h1>Digital Cash Withdrawal</h1>
- <i18n.Translate wrap="p">
- You are about to withdraw{" "}
- <strong>{renderAmount(details.bankWithdrawDetails.amount)}</strong> from
- your bank account into your wallet.
- </i18n.Translate>
- {selectedExchange ? (
- <p>
- The exchange <strong>{selectedExchange}</strong> will be used as the
- Taler payment service provider.
- </p>
- ) : null}
-
- <div>
- <button
- className="pure-button button-success"
- disabled={!selectedExchange}
- onClick={() => accept()}
- >
- {i18n.str`Accept fees and withdraw`}
- </button>
- <p>
- <span
- role="button"
- tabIndex={0}
- style={{ textDecoration: "underline", cursor: "pointer" }}
- onClick={() => setSelecting(true)}
- >
- {i18n.str`Chose different exchange provider`}
- </span>
- <br />
- <span
- role="button"
- tabIndex={0}
- style={{ textDecoration: "underline", cursor: "pointer" }}
- onClick={() => setCancelled(true)}
- >
- {i18n.str`Cancel withdraw operation`}
- </span>
- </p>
-
- {details.exchangeWithdrawDetails ? (
- <WithdrawDetailView rci={details.exchangeWithdrawDetails} />
- ) : null}
- </div>
- </div>
- );
-}
-
-export function createWithdrawPage(): JSX.Element {
- const url = new URL(document.location.href);
- const talerWithdrawUri = url.searchParams.get("talerWithdrawUri");
- if (!talerWithdrawUri) {
- throw Error("withdraw URI required");
- }
- return <WithdrawalDialog talerWithdrawUri={talerWithdrawUri} />;
-}
diff --git a/src/webex/permissions.ts b/src/webex/permissions.ts
deleted file mode 100644
index bcd357fd6..000000000
--- a/src/webex/permissions.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- This file is part of GNU Taler
- (C) 2020 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/>
- */
-
-export const extendedPermissions = {
- permissions: ["webRequest", "webRequestBlocking"],
- origins: ["http://*/*", "https://*/*"],
-};
diff --git a/src/webex/renderHtml.tsx b/src/webex/renderHtml.tsx
deleted file mode 100644
index 39ff470a2..000000000
--- a/src/webex/renderHtml.tsx
+++ /dev/null
@@ -1,344 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 INRIA
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Helpers functions to render Taler-related data structures to HTML.
- *
- * @author Florian Dold
- */
-
-/**
- * Imports.
- */
-import { AmountJson } from "../util/amounts";
-import * as Amounts from "../util/amounts";
-import { ExchangeWithdrawDetails } from "../types/walletTypes";
-import * as i18n from "./i18n";
-import React from "react";
-import { stringifyTimestamp } from "../util/time";
-
-/**
- * Render amount as HTML, which non-breaking space between
- * decimal value and currency.
- */
-export function renderAmount(amount: AmountJson | string): JSX.Element {
- let a;
- if (typeof amount === "string") {
- a = Amounts.parse(amount);
- } else {
- a = amount;
- }
- if (!a) {
- return <span>(invalid amount)</span>;
- }
- const x = a.value + a.fraction / Amounts.fractionalBase;
- return (
- <span>
- {x}&nbsp;{a.currency}
- </span>
- );
-}
-
-export const AmountView = ({
- amount,
-}: {
- amount: AmountJson | string;
-}): JSX.Element => renderAmount(amount);
-
-/**
- * Abbreviate a string to a given length, and show the full
- * string on hover as a tooltip.
- */
-export function abbrev(s: string, n = 5): JSX.Element {
- let sAbbrev = s;
- if (s.length > n) {
- sAbbrev = s.slice(0, n) + "..";
- }
- return (
- <span className="abbrev" title={s}>
- {sAbbrev}
- </span>
- );
-}
-
-interface CollapsibleState {
- collapsed: boolean;
-}
-
-interface CollapsibleProps {
- initiallyCollapsed: boolean;
- title: string;
-}
-
-/**
- * Component that shows/hides its children when clicking
- * a heading.
- */
-export class Collapsible extends React.Component<
- CollapsibleProps,
- CollapsibleState
-> {
- constructor(props: CollapsibleProps) {
- super(props);
- this.state = { collapsed: props.initiallyCollapsed };
- }
- render(): JSX.Element {
- const doOpen = (e: any): void => {
- this.setState({ collapsed: false });
- e.preventDefault();
- };
- const doClose = (e: any): void => {
- this.setState({ collapsed: true });
- e.preventDefault();
- };
- if (this.state.collapsed) {
- return (
- <h2>
- <a className="opener opener-collapsed" href="#" onClick={doOpen}>
- {" "}
- {this.props.title}
- </a>
- </h2>
- );
- }
- return (
- <div>
- <h2>
- <a className="opener opener-open" href="#" onClick={doClose}>
- {" "}
- {this.props.title}
- </a>
- </h2>
- {this.props.children}
- </div>
- );
- }
-}
-
-function WireFee(props: {
- s: string;
- rci: ExchangeWithdrawDetails;
-}): JSX.Element {
- return (
- <>
- <thead>
- <tr>
- <th colSpan={3}>Wire Method {props.s}</th>
- </tr>
- <tr>
- <th>Applies Until</th>
- <th>Wire Fee</th>
- <th>Closing Fee</th>
- </tr>
- </thead>
- <tbody>
- {props.rci.wireFees.feesForType[props.s].map((f) => (
- <tr key={f.sig}>
- <td>{stringifyTimestamp(f.endStamp)}</td>
- <td>{renderAmount(f.wireFee)}</td>
- <td>{renderAmount(f.closingFee)}</td>
- </tr>
- ))}
- </tbody>
- </>
- );
-}
-
-function AuditorDetailsView(props: {
- rci: ExchangeWithdrawDetails | null;
-}): JSX.Element {
- const rci = props.rci;
- console.log("rci", rci);
- if (!rci) {
- return (
- <p>
- Details will be displayed when a valid exchange provider URL is entered.
- </p>
- );
- }
- if ((rci.exchangeInfo.details?.auditors ?? []).length === 0) {
- return <p>The exchange is not audited by any auditors.</p>;
- }
- return (
- <div>
- {(rci.exchangeInfo.details?.auditors ?? []).map((a) => (
- <div key={a.auditor_pub}>
- <h3>Auditor {a.auditor_url}</h3>
- <p>
- Public key: <ExpanderText text={a.auditor_pub} />
- </p>
- <p>
- Trusted:{" "}
- {rci.trustedAuditorPubs.indexOf(a.auditor_pub) >= 0 ? "yes" : "no"}
- </p>
- <p>
- Audits {a.denomination_keys.length} of {rci.numOfferedDenoms}{" "}
- denominations
- </p>
- </div>
- ))}
- </div>
- );
-}
-
-function FeeDetailsView(props: {
- rci: ExchangeWithdrawDetails | null;
-}): JSX.Element {
- const rci = props.rci;
- if (!rci) {
- return (
- <p>
- Details will be displayed when a valid exchange provider URL is entered.
- </p>
- );
- }
-
- const denoms = rci.selectedDenoms;
- const withdrawFee = renderAmount(rci.withdrawFee);
- const overhead = renderAmount(rci.overhead);
-
- return (
- <div>
- <h3>Overview</h3>
- <p>
- Public key:{" "}
- <ExpanderText
- text={rci.exchangeInfo.details?.masterPublicKey ?? "??"}
- />
- </p>
- <p>
- {i18n.str`Withdrawal fees:`} {withdrawFee}
- </p>
- <p>
- {i18n.str`Rounding loss:`} {overhead}
- </p>
- <p>{i18n.str`Earliest expiration (for deposit): ${stringifyTimestamp(
- rci.earliestDepositExpiration,
- )}`}</p>
- <h3>Coin Fees</h3>
- <div style={{ overflow: "auto" }}>
- <table className="pure-table">
- <thead>
- <tr>
- <th>{i18n.str`# Coins`}</th>
- <th>{i18n.str`Value`}</th>
- <th>{i18n.str`Withdraw Fee`}</th>
- <th>{i18n.str`Refresh Fee`}</th>
- <th>{i18n.str`Deposit Fee`}</th>
- </tr>
- </thead>
- <tbody>
- {denoms.selectedDenoms.map((ds) => {
- return (
- <tr key={ds.denom.denomPub}>
- <td>{ds.count + "x"}</td>
- <td>{renderAmount(ds.denom.value)}</td>
- <td>{renderAmount(ds.denom.feeWithdraw)}</td>
- <td>{renderAmount(ds.denom.feeRefresh)}</td>
- <td>{renderAmount(ds.denom.feeDeposit)}</td>
- </tr>
- );
- })}
- </tbody>
- </table>
- </div>
- <h3>Wire Fees</h3>
- <div style={{ overflow: "auto" }}>
- <table className="pure-table">
- {Object.keys(rci.wireFees.feesForType).map((s) => (
- <WireFee key={s} s={s} rci={rci} />
- ))}
- </table>
- </div>
- </div>
- );
-}
-
-/**
- * Shows details about a withdraw request.
- */
-export function WithdrawDetailView(props: {
- rci: ExchangeWithdrawDetails | null;
-}): JSX.Element {
- const rci = props.rci;
- return (
- <div>
- <Collapsible initiallyCollapsed={true} title="Fee and Spending Details">
- <FeeDetailsView rci={rci} />
- </Collapsible>
- <Collapsible initiallyCollapsed={true} title="Auditor Details">
- <AuditorDetailsView rci={rci} />
- </Collapsible>
- </div>
- );
-}
-
-interface ExpanderTextProps {
- text: string;
-}
-
-/**
- * Show a heading with a toggle to show/hide the expandable content.
- */
-export function ExpanderText({ text }: ExpanderTextProps): JSX.Element {
- return <span>{text}</span>;
-}
-
-export interface LoadingButtonProps {
- loading: boolean;
-}
-
-export function ProgressButton(
- props: React.PropsWithChildren<LoadingButtonProps> &
- React.DetailedHTMLProps<
- React.ButtonHTMLAttributes<HTMLButtonElement>,
- HTMLButtonElement
- >,
-): JSX.Element {
- return (
- <button
- className="pure-button pure-button-primary"
- type="button"
- {...props}
- >
- {props.loading ? (
- <span>
- <object
- className="svg-icon svg-baseline"
- data="/img/spinner-bars.svg"
- />
- </span>
- ) : null}{" "}
- {props.children}
- </button>
- );
-}
-
-export function PageLink(
- props: React.PropsWithChildren<{ pageName: string }>,
-): JSX.Element {
- const url = chrome.extension.getURL(`/${props.pageName}`);
- return (
- <a
- className="actionLink"
- href={url}
- target="_blank"
- rel="noopener noreferrer"
- >
- {props.children}
- </a>
- );
-}
diff --git a/src/webex/wxApi.ts b/src/webex/wxApi.ts
deleted file mode 100644
index 4e11463d6..000000000
--- a/src/webex/wxApi.ts
+++ /dev/null
@@ -1,310 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Interface to the wallet through WebExtension messaging.
- */
-
-/**
- * Imports.
- */
-import { AmountJson } from "../util/amounts";
-import {
- CoinRecord,
- CurrencyRecord,
- DenominationRecord,
- ExchangeRecord,
- ReserveRecord,
-} from "../types/dbTypes";
-import {
- BenchmarkResult,
- ConfirmPayResult,
- SenderWireInfos,
- TipStatus,
- PurchaseDetails,
- WalletDiagnostics,
- PreparePayResult,
- AcceptWithdrawalResponse,
- ExtendedPermissionsResponse,
- BalancesResponse,
-} from "../types/walletTypes";
-
-/**
- * Response with information about available version upgrades.
- */
-export interface UpgradeResponse {
- /**
- * Is a reset required because of a new DB version
- * that can't be atomatically upgraded?
- */
- dbResetRequired: boolean;
-
- /**
- * Current database version.
- */
- currentDbVersion: string;
-
- /**
- * Old db version (if applicable).
- */
- oldDbVersion: string;
-}
-
-/**
- * Error thrown when the function from the backend (via RPC) threw an error.
- */
-export class WalletApiError extends Error {
- constructor(message: string, public detail: any) {
- super(message);
- // restore prototype chain
- Object.setPrototypeOf(this, new.target.prototype);
- }
-}
-
-async function callBackend(
- type: string,
- detail: any,
-): Promise<any> {
- return new Promise<any>((resolve, reject) => {
- chrome.runtime.sendMessage({ type, detail }, (resp) => {
- if (chrome.runtime.lastError) {
- console.log("Error calling backend");
- reject(
- new Error(
- `Error contacting backend: chrome.runtime.lastError.message`,
- ),
- );
- }
- if (typeof resp === "object" && resp && resp.error) {
- console.warn("response error:", resp);
- const e = new WalletApiError(resp.error.message, resp.error);
- reject(e);
- } else {
- resolve(resp);
- }
- });
- });
-}
-
-/**
- * Get all exchanges the wallet knows about.
- */
-export function getExchanges(): Promise<ExchangeRecord[]> {
- return callBackend("get-exchanges", {});
-}
-
-/**
- * Get all currencies the exchange knows about.
- */
-export function getCurrencies(): Promise<CurrencyRecord[]> {
- return callBackend("get-currencies", {});
-}
-
-/**
- * Get information about a specific exchange.
- */
-export function getExchangeInfo(baseUrl: string): Promise<ExchangeRecord> {
- return callBackend("exchange-info", { baseUrl });
-}
-
-/**
- * Replace an existing currency record with the one given. The currency to
- * replace is specified inside the currency record.
- */
-export function updateCurrency(currencyRecord: CurrencyRecord): Promise<void> {
- return callBackend("update-currency", { currencyRecord });
-}
-
-/**
- * Get all reserves the wallet has at an exchange.
- */
-export function getReserves(exchangeBaseUrl: string): Promise<ReserveRecord[]> {
- return callBackend("get-reserves", { exchangeBaseUrl });
-}
-
-/**
- * Get all coins withdrawn from the given exchange.
- */
-export function getCoins(exchangeBaseUrl: string): Promise<CoinRecord[]> {
- return callBackend("get-coins", { exchangeBaseUrl });
-}
-
-/**
- * Get all denoms offered by the given exchange.
- */
-export function getDenoms(
- exchangeBaseUrl: string,
-): Promise<DenominationRecord[]> {
- return callBackend("get-denoms", { exchangeBaseUrl });
-}
-
-/**
- * Start refreshing a coin.
- */
-export function refresh(coinPub: string): Promise<void> {
- return callBackend("refresh-coin", { coinPub });
-}
-
-/**
- * Pay for a proposal.
- */
-export function confirmPay(
- proposalId: string,
- sessionId: string | undefined,
-): Promise<ConfirmPayResult> {
- return callBackend("confirm-pay", { proposalId, sessionId });
-}
-
-/**
- * Check upgrade information
- */
-export function checkUpgrade(): Promise<UpgradeResponse> {
- return callBackend("check-upgrade", {});
-}
-
-/**
- * Reset database
- */
-export function resetDb(): Promise<void> {
- return callBackend("reset-db", {});
-}
-
-/**
- * Get balances for all currencies/exchanges.
- */
-export function getBalance(): Promise<BalancesResponse> {
- return callBackend("balances", {});
-}
-
-/**
- * Get possible sender wire infos for getting money
- * wired from an exchange.
- */
-export function getSenderWireInfos(): Promise<SenderWireInfos> {
- return callBackend("get-sender-wire-infos", {});
-}
-
-/**
- * Return coins to a bank account.
- */
-export function returnCoins(args: {
- amount: AmountJson;
- exchange: string;
- senderWire: string;
-}): Promise<void> {
- return callBackend("return-coins", args);
-}
-
-/**
- * Look up a purchase in the wallet database from
- * the contract terms hash.
- */
-export function getPurchaseDetails(
- proposalId: string,
-): Promise<PurchaseDetails> {
- return callBackend("get-purchase-details", { proposalId });
-}
-
-/**
- * Get the status of processing a tip.
- */
-export function getTipStatus(talerTipUri: string): Promise<TipStatus> {
- return callBackend("get-tip-status", { talerTipUri });
-}
-
-/**
- * Mark a tip as accepted by the user.
- */
-export function acceptTip(talerTipUri: string): Promise<void> {
- return callBackend("accept-tip", { talerTipUri });
-}
-
-/**
- * Download a refund and accept it.
- */
-export function applyRefund(
- refundUrl: string,
-): Promise<{ contractTermsHash: string; proposalId: string }> {
- return callBackend("accept-refund", { refundUrl });
-}
-
-/**
- * Abort a failed payment and try to get a refund.
- */
-export function abortFailedPayment(contractTermsHash: string): Promise<void> {
- return callBackend("abort-failed-payment", { contractTermsHash });
-}
-
-/**
- * Abort a failed payment and try to get a refund.
- */
-export function benchmarkCrypto(repetitions: number): Promise<BenchmarkResult> {
- return callBackend("benchmark-crypto", { repetitions });
-}
-
-/**
- * Get details about a pay operation.
- */
-export function preparePay(talerPayUri: string): Promise<PreparePayResult> {
- return callBackend("prepare-pay", { talerPayUri });
-}
-
-/**
- * Get details about a withdraw operation.
- */
-export function acceptWithdrawal(
- talerWithdrawUri: string,
- selectedExchange: string,
-): Promise<AcceptWithdrawalResponse> {
- return callBackend("accept-withdrawal", {
- talerWithdrawUri,
- selectedExchange,
- });
-}
-
-/**
- * Get diagnostics information
- */
-export function getDiagnostics(): Promise<WalletDiagnostics> {
- return callBackend("get-diagnostics", {});
-}
-
-/**
- * Get diagnostics information
- */
-export function setExtendedPermissions(
- value: boolean,
-): Promise<ExtendedPermissionsResponse> {
- return callBackend("set-extended-permissions", { value });
-}
-
-/**
- * Get diagnostics information
- */
-export function getExtendedPermissions(): Promise<ExtendedPermissionsResponse> {
- return callBackend("get-extended-permissions", {});
-}
-
-export function onUpdateNotification(f: () => void): () => void {
- const port = chrome.runtime.connect({ name: "notifications" });
- const listener = (): void => {
- f();
- };
- port.onMessage.addListener(listener);
- return () => {
- port.onMessage.removeListener(listener);
- };
-}
diff --git a/src/webex/wxBackend.ts b/src/webex/wxBackend.ts
deleted file mode 100644
index 39fcf899e..000000000
--- a/src/webex/wxBackend.ts
+++ /dev/null
@@ -1,575 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 GNUnet e.V.
-
- 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.
-
- 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
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- * Messaging for the WebExtensions wallet. Should contain
- * parts that are specific for WebExtensions, but as little business
- * logic as possible.
- */
-
-/**
- * Imports.
- */
-import { BrowserCryptoWorkerFactory } from "../crypto/workers/cryptoApi";
-import {
- deleteTalerDatabase,
- openTalerDatabase,
- WALLET_DB_MINOR_VERSION,
-} from "../db";
-import { ReturnCoinsRequest, WalletDiagnostics } from "../types/walletTypes";
-import { BrowserHttpLib } from "../util/http";
-import { OpenedPromise, openPromise } from "../util/promiseUtils";
-import { classifyTalerUri, TalerUriType } from "../util/taleruri";
-import { Wallet } from "../wallet";
-import { isFirefox, getPermissionsApi } from "./compat";
-import * as wxApi from "./wxApi";
-import MessageSender = chrome.runtime.MessageSender;
-import { Database } from "../util/query";
-import { extendedPermissions } from "./permissions";
-
-const NeedsWallet = Symbol("NeedsWallet");
-
-/**
- * Currently active wallet instance. Might be unloaded and
- * re-instantiated when the database is reset.
- */
-let currentWallet: Wallet | undefined;
-
-let currentDatabase: IDBDatabase | undefined;
-
-/**
- * Last version if an outdated DB, if applicable.
- */
-let outdatedDbVersion: number | undefined;
-
-const walletInit: OpenedPromise<void> = openPromise<void>();
-
-const notificationPorts: chrome.runtime.Port[] = [];
-
-async function handleMessage(
- sender: MessageSender,
- type: string,
- detail: any,
-): Promise<any> {
- function needsWallet(): Wallet {
- if (!currentWallet) {
- throw NeedsWallet;
- }
- return currentWallet;
- }
- switch (type) {
- case "balances": {
- return needsWallet().getBalances();
- }
- case "dump-db": {
- const db = needsWallet().db;
- return db.exportDatabase();
- }
- case "import-db": {
- const db = needsWallet().db;
- return db.importDatabase(detail.dump);
- }
- case "ping": {
- return Promise.resolve();
- }
- case "reset-db": {
- deleteTalerDatabase(indexedDB);
- setBadgeText({ text: "" });
- console.log("reset done");
- if (!currentWallet) {
- reinitWallet();
- }
- return Promise.resolve({});
- }
- case "confirm-pay": {
- if (typeof detail.proposalId !== "string") {
- throw Error("proposalId must be string");
- }
- return needsWallet().confirmPay(detail.proposalId, detail.sessionId);
- }
- case "exchange-info": {
- if (!detail.baseUrl) {
- return Promise.resolve({ error: "bad url" });
- }
- return needsWallet().updateExchangeFromUrl(detail.baseUrl);
- }
- case "get-exchanges": {
- return needsWallet().getExchangeRecords();
- }
- case "get-currencies": {
- return needsWallet().getCurrencies();
- }
- case "update-currency": {
- return needsWallet().updateCurrency(detail.currencyRecord);
- }
- case "get-reserves": {
- if (typeof detail.exchangeBaseUrl !== "string") {
- return Promise.reject(Error("exchangeBaseUrl missing"));
- }
- return needsWallet().getReserves(detail.exchangeBaseUrl);
- }
- case "get-coins": {
- if (typeof detail.exchangeBaseUrl !== "string") {
- return Promise.reject(Error("exchangBaseUrl missing"));
- }
- return needsWallet().getCoinsForExchange(detail.exchangeBaseUrl);
- }
- case "get-denoms": {
- if (typeof detail.exchangeBaseUrl !== "string") {
- return Promise.reject(Error("exchangBaseUrl missing"));
- }
- return needsWallet().getDenoms(detail.exchangeBaseUrl);
- }
- case "refresh-coin": {
- if (typeof detail.coinPub !== "string") {
- return Promise.reject(Error("coinPub missing"));
- }
- return needsWallet().refresh(detail.coinPub);
- }
- case "get-sender-wire-infos": {
- return needsWallet().getSenderWireInfos();
- }
- case "return-coins": {
- const d = {
- amount: detail.amount,
- exchange: detail.exchange,
- senderWire: detail.senderWire,
- };
- const req = ReturnCoinsRequest.checked(d);
- return needsWallet().returnCoins(req);
- }
- case "check-upgrade": {
- let dbResetRequired = false;
- if (!currentWallet) {
- dbResetRequired = true;
- }
- const resp: wxApi.UpgradeResponse = {
- currentDbVersion: WALLET_DB_MINOR_VERSION.toString(),
- dbResetRequired,
- oldDbVersion: (outdatedDbVersion || "unknown").toString(),
- };
- return resp;
- }
- case "get-purchase-details": {
- const proposalId = detail.proposalId;
- if (!proposalId) {
- throw Error("proposalId missing");
- }
- if (typeof proposalId !== "string") {
- throw Error("proposalId must be a string");
- }
- return needsWallet().getPurchaseDetails(proposalId);
- }
- case "accept-refund":
- return needsWallet().applyRefund(detail.refundUrl);
- case "get-tip-status": {
- return needsWallet().getTipStatus(detail.talerTipUri);
- }
- case "accept-tip": {
- return needsWallet().acceptTip(detail.talerTipUri);
- }
- case "abort-failed-payment": {
- if (!detail.contractTermsHash) {
- throw Error("contracTermsHash not given");
- }
- return needsWallet().abortFailedPayment(detail.contractTermsHash);
- }
- case "benchmark-crypto": {
- if (!detail.repetitions) {
- throw Error("repetitions not given");
- }
- return needsWallet().benchmarkCrypto(detail.repetitions);
- }
- case "accept-withdrawal": {
- return needsWallet().acceptWithdrawal(
- detail.talerWithdrawUri,
- detail.selectedExchange,
- );
- }
- case "get-diagnostics": {
- const manifestData = chrome.runtime.getManifest();
- const errors: string[] = [];
- let firefoxIdbProblem = false;
- let dbOutdated = false;
- try {
- await walletInit.promise;
- } catch (e) {
- errors.push("Error during wallet initialization: " + e);
- if (
- currentDatabase === undefined &&
- outdatedDbVersion === undefined &&
- isFirefox()
- ) {
- firefoxIdbProblem = true;
- }
- }
- if (!currentWallet) {
- errors.push("Could not create wallet backend.");
- }
- if (!currentDatabase) {
- errors.push("Could not open database");
- }
- if (outdatedDbVersion !== undefined) {
- errors.push(`Outdated DB version: ${outdatedDbVersion}`);
- dbOutdated = true;
- }
- const diagnostics: WalletDiagnostics = {
- walletManifestDisplayVersion:
- manifestData.version_name || "(undefined)",
- walletManifestVersion: manifestData.version,
- errors,
- firefoxIdbProblem,
- dbOutdated,
- };
- return diagnostics;
- }
- case "prepare-pay":
- return needsWallet().preparePayForUri(detail.talerPayUri);
- case "set-extended-permissions": {
- const newVal = detail.value;
- console.log("new extended permissions value", newVal);
- if (newVal) {
- setupHeaderListener();
- return { newValue: true };
- } else {
- await new Promise((resolve, reject) => {
- getPermissionsApi().remove(extendedPermissions, (rem) => {
- console.log("permissions removed:", rem);
- resolve();
- });
- });
- return { newVal: false };
- }
- }
- case "get-extended-permissions": {
- const res = await new Promise((resolve, reject) => {
- getPermissionsApi().contains(extendedPermissions, (result: boolean) => {
- resolve(result);
- });
- });
- return { newValue: res };
- }
- default:
- console.error(`Request type ${type} unknown`);
- console.error(`Request detail was ${detail}`);
- return {
- error: {
- message: `request type ${type} unknown`,
- requestType: type,
- },
- };
- }
-}
-
-async function dispatch(
- req: any,
- sender: any,
- sendResponse: any,
-): Promise<void> {
- try {
- const p = handleMessage(sender, req.type, req.detail);
- const r = await p;
- try {
- sendResponse(r);
- } catch (e) {
- // might fail if tab disconnected
- }
- } catch (e) {
- console.log(`exception during wallet handler for '${req.type}'`);
- console.log("request", req);
- console.error(e);
- let stack;
- try {
- stack = e.stack.toString();
- } catch (e) {
- // might fail
- }
- try {
- sendResponse({
- error: {
- message: e.message,
- stack,
- },
- });
- } catch (e) {
- console.log(e);
- // might fail if tab disconnected
- }
- }
-}
-
-function getTab(tabId: number): Promise<chrome.tabs.Tab> {
- return new Promise((resolve, reject) => {
- chrome.tabs.get(tabId, (tab: chrome.tabs.Tab) => resolve(tab));
- });
-}
-
-function setBadgeText(options: chrome.browserAction.BadgeTextDetails): void {
- // not supported by all browsers ...
- if (chrome && chrome.browserAction && chrome.browserAction.setBadgeText) {
- chrome.browserAction.setBadgeText(options);
- } else {
- console.warn("can't set badge text, not supported", options);
- }
-}
-
-function waitMs(timeoutMs: number): Promise<void> {
- return new Promise((resolve, reject) => {
- const bgPage = chrome.extension.getBackgroundPage();
- if (!bgPage) {
- reject("fatal: no background page");
- return;
- }
- bgPage.setTimeout(() => resolve(), timeoutMs);
- });
-}
-
-function makeSyncWalletRedirect(
- url: string,
- tabId: number,
- oldUrl: string,
- params?: { [name: string]: string | undefined },
-): Record<string, unknown> {
- const innerUrl = new URL(chrome.extension.getURL("/" + url));
- if (params) {
- for (const key in params) {
- const p = params[key];
- if (p) {
- innerUrl.searchParams.set(key, p);
- }
- }
- }
- if (isFirefox()) {
- // Some platforms don't support the sync redirect (yet), so fall back to
- // async redirect after a timeout.
- const doit = async (): Promise<void> => {
- await waitMs(150);
- const tab = await getTab(tabId);
- if (tab.url === oldUrl) {
- chrome.tabs.update(tabId, { url: innerUrl.href });
- }
- };
- doit();
- }
- console.log("redirecting to", innerUrl.href);
- chrome.tabs.update(tabId, { url: innerUrl.href });
- return { redirectUrl: innerUrl.href };
-}
-
-async function reinitWallet(): Promise<void> {
- if (currentWallet) {
- currentWallet.stop();
- currentWallet = undefined;
- }
- currentDatabase = undefined;
- setBadgeText({ text: "" });
- try {
- currentDatabase = await openTalerDatabase(indexedDB, reinitWallet);
- } catch (e) {
- console.error("could not open database", e);
- walletInit.reject(e);
- return;
- }
- const http = new BrowserHttpLib();
- console.log("setting wallet");
- const wallet = new Wallet(
- new Database(currentDatabase),
- http,
- new BrowserCryptoWorkerFactory(),
- );
- wallet.addNotificationListener((x) => {
- for (const x of notificationPorts) {
- try {
- x.postMessage({ type: "notification" });
- } catch (e) {
- console.error(e);
- }
- }
- });
- wallet.runRetryLoop().catch((e) => {
- console.log("error during wallet retry loop", e);
- });
- // Useful for debugging in the background page.
- (window as any).talerWallet = wallet;
- currentWallet = wallet;
- walletInit.resolve();
-}
-
-try {
- // This needs to be outside of main, as Firefox won't fire the event if
- // the listener isn't created synchronously on loading the backend.
- chrome.runtime.onInstalled.addListener((details) => {
- console.log("onInstalled with reason", details.reason);
- if (details.reason === "install") {
- const url = chrome.extension.getURL("/welcome.html");
- chrome.tabs.create({ active: true, url: url });
- }
- });
-} catch (e) {
- console.error(e);
-}
-
-function headerListener(
- details: chrome.webRequest.WebResponseHeadersDetails,
-): chrome.webRequest.BlockingResponse | undefined {
- console.log("header listener");
- if (chrome.runtime.lastError) {
- console.error(chrome.runtime.lastError);
- return;
- }
- const wallet = currentWallet;
- if (!wallet) {
- console.warn("wallet not available while handling header");
- return;
- }
- console.log("in header listener");
- if (details.statusCode === 402 || details.statusCode === 202) {
- console.log(`got 402/202 from ${details.url}`);
- for (const header of details.responseHeaders || []) {
- if (header.name.toLowerCase() === "taler") {
- const talerUri = header.value || "";
- const uriType = classifyTalerUri(talerUri);
- switch (uriType) {
- case TalerUriType.TalerWithdraw:
- return makeSyncWalletRedirect(
- "withdraw.html",
- details.tabId,
- details.url,
- {
- talerWithdrawUri: talerUri,
- },
- );
- case TalerUriType.TalerPay:
- return makeSyncWalletRedirect(
- "pay.html",
- details.tabId,
- details.url,
- {
- talerPayUri: talerUri,
- },
- );
- case TalerUriType.TalerTip:
- return makeSyncWalletRedirect(
- "tip.html",
- details.tabId,
- details.url,
- {
- talerTipUri: talerUri,
- },
- );
- case TalerUriType.TalerRefund:
- return makeSyncWalletRedirect(
- "refund.html",
- details.tabId,
- details.url,
- {
- talerRefundUri: talerUri,
- },
- );
- case TalerUriType.TalerNotifyReserve:
- Promise.resolve().then(() => {
- const w = currentWallet;
- if (!w) {
- return;
- }
- w.handleNotifyReserve();
- });
- break;
- default:
- console.warn(
- "Response with HTTP 402 has Taler header, but header value is not a taler:// URI.",
- );
- break;
- }
- }
- }
- }
- return;
-}
-
-function setupHeaderListener(): void {
- console.log("setting up header listener");
- // Handlers for catching HTTP requests
- getPermissionsApi().contains(extendedPermissions, (result: boolean) => {
- if (
- chrome.webRequest.onHeadersReceived &&
- chrome.webRequest.onHeadersReceived.hasListener(headerListener)
- ) {
- chrome.webRequest.onHeadersReceived.removeListener(headerListener);
- }
- if (result) {
- console.log("actually adding listener");
- chrome.webRequest.onHeadersReceived.addListener(
- headerListener,
- { urls: ["<all_urls>"] },
- ["responseHeaders", "blocking"],
- );
- }
- chrome.webRequest.handlerBehaviorChanged(() => {
- if (chrome.runtime.lastError) {
- console.error(chrome.runtime.lastError);
- }
- });
- });
-}
-
-/**
- * Main function to run for the WebExtension backend.
- *
- * Sets up all event handlers and other machinery.
- */
-export async function wxMain(): Promise<void> {
- // Explicitly unload the extension page as soon as an update is available,
- // so the update gets installed as soon as possible.
- chrome.runtime.onUpdateAvailable.addListener((details) => {
- console.log("update available:", details);
- chrome.runtime.reload();
- });
- reinitWallet();
-
- // Handlers for messages coming directly from the content
- // script on the page
- chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
- dispatch(req, sender, sendResponse);
- return true;
- });
-
- chrome.runtime.onConnect.addListener((port) => {
- notificationPorts.push(port);
- port.onDisconnect.addListener((discoPort) => {
- const idx = notificationPorts.indexOf(discoPort);
- if (idx >= 0) {
- notificationPorts.splice(idx, 1);
- }
- });
- });
-
- try {
- setupHeaderListener();
- } catch (e) {
- console.log(e);
- }
-
- // On platforms that support it, also listen to external
- // modification of permissions.
- getPermissionsApi().addPermissionsListener((perm) => {
- if (chrome.runtime.lastError) {
- console.error(chrome.runtime.lastError);
- return;
- }
- setupHeaderListener();
- });
-}