summaryrefslogtreecommitdiff
path: root/packages/taler-wallet-core/src
diff options
context:
space:
mode:
authorFlorian Dold <florian.dold@gmail.com>2020-08-03 13:00:48 +0530
committerFlorian Dold <florian.dold@gmail.com>2020-08-03 13:01:05 +0530
commitffd2a62c3f7df94365980302fef3bc3376b48182 (patch)
tree270af6f16b4cc7f5da2afdba55c8bc9dbea5eca5 /packages/taler-wallet-core/src
parentaa481e42675fb7c4dcbbeec0ba1c61e1953b9596 (diff)
downloadwallet-core-ffd2a62c3f7df94365980302fef3bc3376b48182.tar.gz
wallet-core-ffd2a62c3f7df94365980302fef3bc3376b48182.tar.bz2
wallet-core-ffd2a62c3f7df94365980302fef3bc3376b48182.zip
modularize repo, use pnpm, improve typechecking
Diffstat (limited to 'packages/taler-wallet-core/src')
-rw-r--r--packages/taler-wallet-core/src/TalerErrorCode.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/TalerErrorCode.ts3097
-rw-r--r--packages/taler-wallet-core/src/crypto/primitives/kdf.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/crypto/primitives/kdf.ts92
-rw-r--r--packages/taler-wallet-core/src/crypto/primitives/nacl-fast.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/crypto/primitives/nacl-fast.ts1941
-rw-r--r--packages/taler-wallet-core/src/crypto/primitives/sha256.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/crypto/primitives/sha256.ts426
-rw-r--r--packages/taler-wallet-core/src/crypto/talerCrypto-test.ts197
-rw-r--r--packages/taler-wallet-core/src/crypto/talerCrypto.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/crypto/talerCrypto.ts391
-rw-r--r--packages/taler-wallet-core/src/crypto/workers/cryptoApi.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/crypto/workers/cryptoApi.ts446
-rw-r--r--packages/taler-wallet-core/src/crypto/workers/cryptoImplementation.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/crypto/workers/cryptoImplementation.ts579
-rw-r--r--packages/taler-wallet-core/src/crypto/workers/cryptoWorker.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/crypto/workers/cryptoWorker.ts8
-rw-r--r--packages/taler-wallet-core/src/crypto/workers/nodeThreadWorker.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/crypto/workers/nodeThreadWorker.ts183
-rw-r--r--packages/taler-wallet-core/src/crypto/workers/synchronousWorker.ts136
-rw-r--r--packages/taler-wallet-core/src/db.ts66
-rw-r--r--packages/taler-wallet-core/src/headless/NodeHttpLib.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/headless/NodeHttpLib.ts133
-rw-r--r--packages/taler-wallet-core/src/headless/helpers.ts135
-rw-r--r--packages/taler-wallet-core/src/i18n/de.po363
-rw-r--r--packages/taler-wallet-core/src/i18n/en-US.po294
-rw-r--r--packages/taler-wallet-core/src/i18n/fr.po290
-rw-r--r--packages/taler-wallet-core/src/i18n/index.ts78
-rw-r--r--packages/taler-wallet-core/src/i18n/it.po290
-rw-r--r--packages/taler-wallet-core/src/i18n/poheader26
-rw-r--r--packages/taler-wallet-core/src/i18n/strings-prelude17
-rw-r--r--packages/taler-wallet-core/src/i18n/strings.ts373
-rw-r--r--packages/taler-wallet-core/src/i18n/sv.po388
-rw-r--r--packages/taler-wallet-core/src/i18n/taler-wallet-webex.pot290
-rw-r--r--packages/taler-wallet-core/src/index.ts75
-rw-r--r--packages/taler-wallet-core/src/operations/balance.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/operations/balance.ts153
-rw-r--r--packages/taler-wallet-core/src/operations/errors.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/operations/errors.ts121
-rw-r--r--packages/taler-wallet-core/src/operations/exchanges.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/operations/exchanges.ts555
-rw-r--r--packages/taler-wallet-core/src/operations/pay.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/operations/pay.ts1148
-rw-r--r--packages/taler-wallet-core/src/operations/pending.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/operations/pending.ts458
-rw-r--r--packages/taler-wallet-core/src/operations/recoup.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/operations/recoup.ts412
-rw-r--r--packages/taler-wallet-core/src/operations/refresh.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/operations/refresh.ts573
-rw-r--r--packages/taler-wallet-core/src/operations/refund.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/operations/refund.ts438
-rw-r--r--packages/taler-wallet-core/src/operations/reserves.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/operations/reserves.ts841
-rw-r--r--packages/taler-wallet-core/src/operations/state.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/operations/state.ts65
-rw-r--r--packages/taler-wallet-core/src/operations/testing.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/operations/testing.ts156
-rw-r--r--packages/taler-wallet-core/src/operations/tip.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/operations/tip.ts343
-rw-r--r--packages/taler-wallet-core/src/operations/transactions.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/operations/transactions.ts288
-rw-r--r--packages/taler-wallet-core/src/operations/versions.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/operations/versions.ts38
-rw-r--r--packages/taler-wallet-core/src/operations/withdraw-test.ts332
-rw-r--r--packages/taler-wallet-core/src/operations/withdraw.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/operations/withdraw.ts759
-rw-r--r--packages/taler-wallet-core/src/types/ReserveStatus.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/types/ReserveStatus.ts57
-rw-r--r--packages/taler-wallet-core/src/types/ReserveTransaction.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/types/ReserveTransaction.ts250
-rw-r--r--packages/taler-wallet-core/src/types/dbTypes.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/types/dbTypes.ts1819
-rw-r--r--packages/taler-wallet-core/src/types/notifications.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/types/notifications.ts255
-rw-r--r--packages/taler-wallet-core/src/types/pending.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/types/pending.ts258
-rw-r--r--packages/taler-wallet-core/src/types/schemacore.ts58
-rw-r--r--packages/taler-wallet-core/src/types/talerTypes.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/types/talerTypes.ts1272
-rw-r--r--packages/taler-wallet-core/src/types/transactions.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/types/transactions.ts314
-rw-r--r--packages/taler-wallet-core/src/types/types-test.ts55
-rw-r--r--packages/taler-wallet-core/src/types/walletTypes.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/types/walletTypes.ts516
-rw-r--r--packages/taler-wallet-core/src/util/RequestThrottler.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/util/RequestThrottler.ts129
-rw-r--r--packages/taler-wallet-core/src/util/amounts-test.ts140
-rw-r--r--packages/taler-wallet-core/src/util/amounts.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/util/amounts.ts384
-rw-r--r--packages/taler-wallet-core/src/util/assertUnreachable.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/util/assertUnreachable.ts19
-rw-r--r--packages/taler-wallet-core/src/util/asyncMemo.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/util/asyncMemo.ts87
-rw-r--r--packages/taler-wallet-core/src/util/codec-test.ts78
-rw-r--r--packages/taler-wallet-core/src/util/codec.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/util/codec.ts406
-rw-r--r--packages/taler-wallet-core/src/util/helpers-test.ts46
-rw-r--r--packages/taler-wallet-core/src/util/helpers.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/util/helpers.ts148
-rw-r--r--packages/taler-wallet-core/src/util/http.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/util/http.ts237
-rw-r--r--packages/taler-wallet-core/src/util/libtoolVersion-test.ts48
-rw-r--r--packages/taler-wallet-core/src/util/libtoolVersion.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/util/libtoolVersion.ts88
-rw-r--r--packages/taler-wallet-core/src/util/logging.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/util/logging.ts89
-rw-r--r--packages/taler-wallet-core/src/util/payto-test.ts31
-rw-r--r--packages/taler-wallet-core/src/util/payto.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/util/payto.ts71
-rw-r--r--packages/taler-wallet-core/src/util/promiseUtils.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/util/promiseUtils.ts60
-rw-r--r--packages/taler-wallet-core/src/util/query.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/util/query.ts576
-rw-r--r--packages/taler-wallet-core/src/util/reserveHistoryUtil-test.ts285
-rw-r--r--packages/taler-wallet-core/src/util/reserveHistoryUtil.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/util/reserveHistoryUtil.ts360
-rw-r--r--packages/taler-wallet-core/src/util/talerconfig.ts120
-rw-r--r--packages/taler-wallet-core/src/util/taleruri-test.ts184
-rw-r--r--packages/taler-wallet-core/src/util/taleruri.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/util/taleruri.ts215
-rw-r--r--packages/taler-wallet-core/src/util/testvectors.ts36
-rw-r--r--packages/taler-wallet-core/src/util/time.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/util/time.ts198
-rw-r--r--packages/taler-wallet-core/src/util/timer.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/util/timer.ts165
-rw-r--r--packages/taler-wallet-core/src/util/url.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/util/url.ts74
-rw-r--r--packages/taler-wallet-core/src/util/wire.ts51
-rw-r--r--packages/taler-wallet-core/src/wallet-test.ts121
-rw-r--r--packages/taler-wallet-core/src/wallet.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/wallet.ts882
-rw-r--r--packages/taler-wallet-core/src/walletCoreApiHandler.d.ts.map1
-rw-r--r--packages/taler-wallet-core/src/walletCoreApiHandler.ts318
133 files changed, 27546 insertions, 0 deletions
diff --git a/packages/taler-wallet-core/src/TalerErrorCode.d.ts.map b/packages/taler-wallet-core/src/TalerErrorCode.d.ts.map
new file mode 100644
index 000000000..87926875d
--- /dev/null
+++ b/packages/taler-wallet-core/src/TalerErrorCode.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"TalerErrorCode.d.ts","sourceRoot":"","sources":["TalerErrorCode.ts"],"names":[],"mappings":"AAuBA,oBAAY,cAAc;IAGxB;;;;OAIG;IACH,IAAI,IAAI;IAER;;;;OAIG;IACH,OAAO,IAAI;IAEX;;;;OAIG;IACH,gBAAgB,IAAI;IAEpB;;;;OAIG;IACH,eAAe,IAAI;IAEnB;;;;OAIG;IACH,0BAA0B,IAAI;IAE9B;;;;OAIG;IACH,0BAA0B,IAAI;IAE9B;;;;OAIG;IACH,OAAO,IAAI;IAEX;;;;OAIG;IACH,uBAAuB,IAAI;IAE3B;;;;OAIG;IACH,cAAc,IAAI;IAElB;;;;OAIG;IACH,iBAAiB,IAAI;IAErB;;;;OAIG;IACH,gBAAgB,KAAK;IAErB;;;;OAIG;IACH,YAAY,KAAK;IAEjB;;;;OAIG;IACH,wBAAwB,KAAK;IAE7B;;;;OAIG;IACH,0BAA0B,KAAK;IAE/B;;;;OAIG;IACH,iBAAiB,KAAK;IAEtB;;;;OAIG;IACH,uBAAuB,KAAK;IAE5B;;;;OAIG;IACH,oBAAoB,KAAK;IAEzB;;;;OAIG;IACH,eAAe,KAAK;IAEpB;;;;OAIG;IACH,eAAe,OAAO;IAEtB;;;;OAIG;IACH,eAAe,OAAO;IAEtB;;;;OAIG;IACH,qBAAqB,OAAO;IAE5B;;;;OAIG;IACH,yBAAyB,OAAO;IAEhC;;;;OAIG;IACH,oBAAoB,OAAO;IAE3B;;;;OAIG;IACH,YAAY,OAAO;IAEnB;;;;OAIG;IACH,yBAAyB,OAAO;IAEhC;;;;OAIG;IACH,iBAAiB,OAAO;IAExB;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GAAG,OAAO;CAEX"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/TalerErrorCode.ts b/packages/taler-wallet-core/src/TalerErrorCode.ts
new file mode 100644
index 000000000..d45b1064f
--- /dev/null
+++ b/packages/taler-wallet-core/src/TalerErrorCode.ts
@@ -0,0 +1,3097 @@
+/*
+ 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/packages/taler-wallet-core/src/crypto/primitives/kdf.d.ts.map b/packages/taler-wallet-core/src/crypto/primitives/kdf.d.ts.map
new file mode 100644
index 000000000..0495859a5
--- /dev/null
+++ b/packages/taler-wallet-core/src/crypto/primitives/kdf.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"kdf.d.ts","sourceRoot":"","sources":["kdf.ts"],"names":[],"mappings":"AAmBA,wBAAgB,MAAM,CAAC,IAAI,EAAE,UAAU,GAAG,UAAU,CAEnD;AAED,wBAAgB,IAAI,CAClB,MAAM,EAAE,CAAC,CAAC,EAAE,UAAU,KAAK,UAAU,EACrC,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,UAAU,EACf,OAAO,EAAE,UAAU,GAClB,UAAU,CAuBZ;AAED,wBAAgB,UAAU,CAAC,GAAG,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU,GAAG,UAAU,CAE3E;AAED,wBAAgB,UAAU,CAAC,GAAG,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU,GAAG,UAAU,CAE3E;AAED,wBAAgB,GAAG,CACjB,YAAY,EAAE,MAAM,EACpB,GAAG,EAAE,UAAU,EACf,IAAI,EAAE,UAAU,EAChB,IAAI,EAAE,UAAU,GACf,UAAU,CAyBZ"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/crypto/primitives/kdf.ts b/packages/taler-wallet-core/src/crypto/primitives/kdf.ts
new file mode 100644
index 000000000..edc681bc1
--- /dev/null
+++ b/packages/taler-wallet-core/src/crypto/primitives/kdf.ts
@@ -0,0 +1,92 @@
+/*
+ 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/packages/taler-wallet-core/src/crypto/primitives/nacl-fast.d.ts.map b/packages/taler-wallet-core/src/crypto/primitives/nacl-fast.d.ts.map
new file mode 100644
index 000000000..6dab0be11
--- /dev/null
+++ b/packages/taler-wallet-core/src/crypto/primitives/nacl-fast.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"nacl-fast.d.ts","sourceRoot":"","sources":["nacl-fast.ts"],"names":[],"mappings":"AA8zCA;;GAEG;AACH,qBAAa,SAAS;IACpB,OAAO,CAAC,EAAE,CAAqB;IAC/B,OAAO,CAAC,EAAE,CAAqB;IAE/B,OAAO,CAAC,IAAI,CAAuB;IACnC,OAAO,CAAC,CAAC,CAAK;IACd,OAAO,CAAC,KAAK,CAAK;;IAsBlB,MAAM,CAAC,IAAI,EAAE,UAAU,GAAG,SAAS;IAuBnC,MAAM,IAAI,UAAU;CAgBrB;AAqTD,wBAAgB,WAAW,CAAC,CAAC,EAAE,MAAM,GAAG,UAAU,CAIjD;AAED,wBAAgB,UAAU,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,UAAU,GAAG,UAAU,CAOnE;AAED,wBAAgB,eAAe,CAAC,CAAC,EAAE,UAAU,GAAG,UAAU,CAMzD;AAED,eAAO,MAAM,uBAAuB,KAAgC,CAAC;AACrE,eAAO,MAAM,6BAA6B,KAA0B,CAAC;AAErE,wBAAgB,IAAI,CAAC,GAAG,EAAE,UAAU,EAAE,SAAS,EAAE,UAAU,GAAG,UAAU,CAOvE;AAED,wBAAgB,SAAS,CACvB,SAAS,EAAE,UAAU,EACrB,SAAS,EAAE,UAAU,GACpB,UAAU,GAAG,IAAI,CAUnB;AAED,wBAAgB,aAAa,CAC3B,GAAG,EAAE,UAAU,EACf,SAAS,EAAE,UAAU,GACpB,UAAU,CAKZ;AAED,wBAAgB,oBAAoB,CAClC,GAAG,EAAE,UAAU,EACf,GAAG,EAAE,UAAU,EACf,SAAS,EAAE,UAAU,GACpB,OAAO,CAWT;AAED,wBAAgB,YAAY,IAAI;IAC9B,SAAS,EAAE,UAAU,CAAC;IACtB,SAAS,EAAE,UAAU,CAAC;CACvB,CAKA;AAED,wBAAgB,oCAAoC,CAClD,SAAS,EAAE,UAAU,GACpB,UAAU,CAmBZ;AAED,wBAAgB,0BAA0B,CACxC,SAAS,EAAE,UAAU,GACpB;IACD,SAAS,EAAE,UAAU,CAAC;IACtB,SAAS,EAAE,UAAU,CAAC;CACvB,CAOA;AAED,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,UAAU,GACf;IACD,SAAS,EAAE,UAAU,CAAC;IACtB,SAAS,EAAE,UAAU,CAAC;CACvB,CAQA;AAED,eAAO,MAAM,oBAAoB,KAA6B,CAAC;AAC/D,eAAO,MAAM,oBAAoB,KAA6B,CAAC;AAC/D,eAAO,MAAM,eAAe,KAAwB,CAAC;AACrD,eAAO,MAAM,oBAAoB,KAAoB,CAAC;AAEtD,wBAAgB,IAAI,CAAC,GAAG,EAAE,UAAU,GAAG,UAAU,CAKhD;AAED,eAAO,MAAM,eAAe,KAAoB,CAAC;AAEjD,wBAAgB,MAAM,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,UAAU,GAAG,OAAO,CAM5D;AAED,wBAAgB,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,MAAM,KAAK,IAAI,GAAG,IAAI,CAEpE;AAED,wBAAgB,6BAA6B,CAC3C,UAAU,EAAE,UAAU,GACrB,UAAU,CAqBZ"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/crypto/primitives/nacl-fast.ts b/packages/taler-wallet-core/src/crypto/primitives/nacl-fast.ts
new file mode 100644
index 000000000..c2d40691a
--- /dev/null
+++ b/packages/taler-wallet-core/src/crypto/primitives/nacl-fast.ts
@@ -0,0 +1,1941 @@
+// 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.
+ // @ts-ignore-error
+ const cr = typeof self !== "undefined" ? self.crypto || self.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/packages/taler-wallet-core/src/crypto/primitives/sha256.d.ts.map b/packages/taler-wallet-core/src/crypto/primitives/sha256.d.ts.map
new file mode 100644
index 000000000..91ebcd392
--- /dev/null
+++ b/packages/taler-wallet-core/src/crypto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AAU,CAKnD;AAGD,wBAAgB,UAAU,CAAC,GAAG,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,GAAG,UAAU,CAKxE"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/crypto/primitives/sha256.ts b/packages/taler-wallet-core/src/crypto/primitives/sha256.ts
new file mode 100644
index 000000000..97723dbfc
--- /dev/null
+++ b/packages/taler-wallet-core/src/crypto/primitives/sha256.ts
@@ -0,0 +1,426 @@
+// 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/packages/taler-wallet-core/src/crypto/talerCrypto-test.ts b/packages/taler-wallet-core/src/crypto/talerCrypto-test.ts
new file mode 100644
index 000000000..b273b0188
--- /dev/null
+++ b/packages/taler-wallet-core/src/crypto/talerCrypto-test.ts
@@ -0,0 +1,197 @@
+/*
+ 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,
+ stringToBytes,
+ bytesToString,
+ rsaVerify,
+} from "./talerCrypto";
+import { sha512, kdf } from "./primitives/kdf";
+import * as nacl from "./primitives/nacl-fast";
+
+test("encoding", (t) => {
+ const s = "Hello, World";
+ const encStr = encodeCrock(stringToBytes(s));
+ const outBuf = decodeCrock(encStr);
+ const sOut = bytesToString(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 =
+ "GA8PC6YH9VF5MW6P2DKTV0W0ZTQ24DZ9EAN5QH3SQXRH7SCZHFMM21ZY05F0BS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M8R0FS58EV16WTRAM1ABBFVNAT3CAEFAZCWP3XHPVBQY5NZVTD5QS2Q8SKJQ2XB30E11CWDN9KTV5CBK4DN72EVG73F3W3BATAKHG";
+
+ 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/packages/taler-wallet-core/src/crypto/talerCrypto.d.ts.map b/packages/taler-wallet-core/src/crypto/talerCrypto.d.ts.map
new file mode 100644
index 000000000..cbc5ba16c
--- /dev/null
+++ b/packages/taler-wallet-core/src/crypto/talerCrypto.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"taler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E,UAAU,CAAC;CACvB;AAED,wBAAgB,kBAAkB,IAAI,YAAY,CAIjD;AAED,wBAAgB,kBAAkB,IAAI,YAAY,CAIjD;AAED,wBAAgB,uBAAuB,IAAI,UAAU,CAEpD;AAED,wBAAgB,IAAI,CAAC,CAAC,EAAE,UAAU,GAAG,UAAU,CAE9C;AAED,wBAAgB,SAAS,CAAC,GAAG,EAAE,UAAU,EAAE,SAAS,EAAE,UAAU,GAAG,UAAU,CAG5E;AAED,wBAAgB,WAAW,CACzB,GAAG,EAAE,UAAU,EACf,GAAG,EAAE,UAAU,EACf,QAAQ,EAAE,UAAU,GACnB,OAAO,CAET;AAED,wBAAgB,iBAAiB,IAAI,IAAI,CAAC,SAAS,CAElD;AAED,MAAM,WAAW,SAAS;IACxB,OAAO,EAAE,UAAU,CAAC;IACpB,QAAQ,EAAE,UAAU,CAAC;IACrB,GAAG,EAAE,UAAU,CAAC;CACjB;AAED,wBAAgB,oBAAoB,CAClC,UAAU,EAAE,UAAU,EACtB,UAAU,EAAE,MAAM,GACjB,SAAS,CAcX"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/crypto/talerCrypto.ts b/packages/taler-wallet-core/src/crypto/talerCrypto.ts
new file mode 100644
index 000000000..3ce5491c1
--- /dev/null
+++ b/packages/taler-wallet-core/src/crypto/talerCrypto.ts
@@ -0,0 +1,391 @@
+/*
+ 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";
+
+// @ts-ignore
+const decoder = new TextDecoder();
+if (typeof decoder !== "object") {
+ throw Error("FATAL: TextDecoder not available");
+}
+
+// @ts-ignore
+const encoder = new TextEncoder();
+if (typeof encoder !== "object") {
+ throw Error("FATAL: TextEncoder not available");
+}
+
+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 {
+ return encoder.encode(s);
+}
+
+export function bytesToString(b: Uint8Array): string {
+ return decoder.decode(b);
+}
+
+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/packages/taler-wallet-core/src/crypto/workers/cryptoApi.d.ts.map b/packages/taler-wallet-core/src/crypto/workers/cryptoApi.d.ts.map
new file mode 100644
index 000000000..d8ab05823
--- /dev/null
+++ b/packages/taler-wallet-core/src/crypto/workers/cryptoApi.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"cryptoApi.d.ts","sourceRoot":"","sources":["cryptoApi.ts"],"names":[],"mappings":"AAgBA;;;GAGG;AAEH;;GAEG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EACL,UAAU,EACV,kBAAkB,EAClB,oBAAoB,EACpB,WAAW,EACX,OAAO,EACP,yBAAyB,EAC1B,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C,OAAO,EAAE,aAAa,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAE9E,OAAO,EACL,eAAe,EACf,sBAAsB,EACtB,uBAAuB,EACvB,WAAW,EACZ,MAAM,yBAAyB,CAAC;AAEjC,OAAO,KAAK,KAAK,MAAM,kBAAkB,CAAC;AAK1C;;GAEG;AACH,UAAU,WAAW;IACnB;;OAEG;IACH,CAAC,EAAE,YAAY,GAAG,IAAI,CAAC;IAEvB;;OAEG;IACH,eAAe,EAAE,QAAQ,GAAG,IAAI,CAAC;IAEjC;;OAEG;IACH,sBAAsB,EAAE,KAAK,CAAC,WAAW,GAAG,IAAI,CAAC;CAClD;AAED,UAAU,QAAQ;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,GAAG,EAAE,CAAC;IACZ,OAAO,EAAE,GAAG,CAAC;IACb,MAAM,EAAE,GAAG,CAAC;IAEZ;;OAEG;IACH,KAAK,E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C;CAGzD"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/crypto/workers/cryptoApi.ts b/packages/taler-wallet-core/src/crypto/workers/cryptoApi.ts
new file mode 100644
index 000000000..a272d5724
--- /dev/null
+++ b/packages/taler-wallet-core/src/crypto/workers/cryptoApi.ts
@@ -0,0 +1,446 @@
+/*
+ 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;
+}
+
+/**
+ * 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: any) => this.handleWorkerMessage(ws, m);
+ worker.onerror = (e: any) => 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: any): 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: any): 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/packages/taler-wallet-core/src/crypto/workers/cryptoImplementation.d.ts.map b/packages/taler-wallet-core/src/crypto/workers/cryptoImplementation.d.ts.map
new file mode 100644
index 000000000..192c54d05
--- /dev/null
+++ b/packages/taler-wallet-core/src/crypto/workers/cryptoImplementation.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"cryptoImplementation.d.ts","sourceRoot":"","sources":["cryptoImplementation.ts"],"names":[],"mappings":"AAgBA;;;;;;GAMG;AAEH;;GAEG;AAEH,OAAO,EACL,UAAU,EACV,kBAAkB,EAElB,oBAAoB,EACpB,WAAW,EACX,OAAO,EAEP,yBAAyB,EAC1B,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAC9E,OAAO,EACL,eAAe,EACf,sBAAsB,EACtB,uBAAuB,EACvB,WAAW,EACZ,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,UAAU,EAAW,MAAM,oBAAoB,CAAC;AAgGzD,qBAAa,oBAAoB;IAC/B,MAAM,CAAC,aAAa,UAAS;IAE7B;;;OAGG;IACH,cAAc,CAAC,GAAG,EAAE,uBAAuB,GAAG,sBAAsB;IAoCpE;;OAEG;IACH,iBAAiB,CAAC,KAAK,EAAE,kBAAkB,GAAG,WAAW;IAmBzD;;OAEG;IACH,mBAAmB,CAAC,IAAI,EAAE,UAAU,GAAG,aAAa;IAoBpD;;OAEG;IACH,uBAAuB,CACrB,GAAG,EAAE,MAAM,EACX,YAAY,EAAE,MAAM,EACpB,WAAW,EAAE,MAAM,GAClB,OAAO;IASV;;OAEG;IACH,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO;IAarE;;OAEG;IACH,YAAY,CAAC,KAAK,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO;IAmBnE,kBAAkB,CAChB,QAAQ,EAAE,MAAM,EAChB,GAAG,EAAE,MAAM,EACX,SAAS,EAAE,MAAM,GAChB,OAAO;IAWV;;OAEG;IACH,kBAAkB,IAAI;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE;IAQnD;;OAEG;IACH,UAAU,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM;IAS9D;;OAEG;IACH,SAAS,CAAC,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO;IAIvD;;;OAGG;IACH,qBAAqB,CAAC,WAAW,EAAE,WAAW,GAAG,qBAAqB;IAyBtE;;OAEG;IACH,oBAAoB,CAClB,eAAe,EAAE,MAAM,EACvB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,UAAU,EACpB,aAAa,EAAE,yBAAyB,EACxC,OAAO,EAAE,UAAU,GAClB,oBAAoB;IA2HvB;;OAEG;IACH,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM;IAK/B;;OAEG;IACH,WAAW,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM;IAIzC,YAAY,CACV,WAAW,EAAE,MAAM,EACnB,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,EAClB,WAAW,EAAE,MAAM,EACnB,MAAM,EAAE,MAAM,GACb,MAAM;IAaT,SAAS,CAAC,WAAW,EAAE,MAAM,GAAG,eAAe;CAsDhD"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/crypto/workers/cryptoImplementation.ts b/packages/taler-wallet-core/src/crypto/workers/cryptoImplementation.ts
new file mode 100644
index 000000000..4195ebded
--- /dev/null
+++ b/packages/taler-wallet-core/src/crypto/workers/cryptoImplementation.ts
@@ -0,0 +1,579 @@
+/*
+ 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 curr = stringToBytes(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 b = stringToBytes(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/packages/taler-wallet-core/src/crypto/workers/cryptoWorker.d.ts.map b/packages/taler-wallet-core/src/crypto/workers/cryptoWorker.d.ts.map
new file mode 100644
index 000000000..cfdedef09
--- /dev/null
+++ b/packages/taler-wallet-core/src/crypto/workers/cryptoWorker.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"cryptoWorker.d.ts","sourceRoot":"","sources":["cryptoWorker.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,YAAY;IAC3B,WAAW,CAAC,OAAO,EAAE,GAAG,GAAG,IAAI,CAAC;IAEhC,SAAS,IAAI,IAAI,CAAC;IAElB,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IAC1C,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;CACzC"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/crypto/workers/cryptoWorker.ts b/packages/taler-wallet-core/src/crypto/workers/cryptoWorker.ts
new file mode 100644
index 000000000..9f3ee6f50
--- /dev/null
+++ b/packages/taler-wallet-core/src/crypto/workers/cryptoWorker.ts
@@ -0,0 +1,8 @@
+export interface CryptoWorker {
+ postMessage(message: any): void;
+
+ terminate(): void;
+
+ onmessage: ((m: any) => void) | undefined;
+ onerror: ((m: any) => void) | undefined;
+}
diff --git a/packages/taler-wallet-core/src/crypto/workers/nodeThreadWorker.d.ts.map b/packages/taler-wallet-core/src/crypto/workers/nodeThreadWorker.d.ts.map
new file mode 100644
index 000000000..d89774cd5
--- /dev/null
+++ b/packages/taler-wallet-core/src/crypto/workers/nodeThreadWorker.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"nodeThreadWorker.d.ts","sourceRoot":"","sources":["nodeThreadWorker.ts"],"names":[],"mappings":"AAgBA;;GAEG;AACH,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAiC9C;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,GAAG,GAAG,IAAI,CA6ClD;AAED,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,KAAK,GAAG,IAAI,CAEhD;AAED,qBAAa,6BAA8B,YAAW,mBAAmB;IACvE,WAAW,IAAI,YAAY;IAO3B,cAAc,IAAI,MAAM;CAGzB"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/crypto/workers/nodeThreadWorker.ts b/packages/taler-wallet-core/src/crypto/workers/nodeThreadWorker.ts
new file mode 100644
index 000000000..6c9dfc569
--- /dev/null
+++ b/packages/taler-wallet-core/src/crypto/workers/nodeThreadWorker.ts
@@ -0,0 +1,183 @@
+/*
+ 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/packages/taler-wallet-core/src/crypto/workers/synchronousWorker.ts b/packages/taler-wallet-core/src/crypto/workers/synchronousWorker.ts
new file mode 100644
index 000000000..5327670bd
--- /dev/null
+++ b/packages/taler-wallet-core/src/crypto/workers/synchronousWorker.ts
@@ -0,0 +1,136 @@
+/*
+ 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");
+ }
+ return new SynchronousCryptoWorker();
+ }
+
+ 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/packages/taler-wallet-core/src/db.ts b/packages/taler-wallet-core/src/db.ts
new file mode 100644
index 000000000..a6eeb1205
--- /dev/null
+++ b/packages/taler-wallet-core/src/db.ts
@@ -0,0 +1,66 @@
+import { Stores } from "./types/dbTypes";
+import { openDatabase, Database, Store, Index } from "./util/query";
+import type { idbtypes } from "idb-bridge";
+
+/**
+ * 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: idbtypes.IDBFactory,
+ onVersionChange: () => void,
+): Promise<idbtypes.IDBDatabase> {
+ const onUpgradeNeeded = (
+ db: idbtypes.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: idbtypes.IDBFactory): void {
+ Database.deleteDatabase(idbFactory, TALER_DB_NAME);
+}
diff --git a/packages/taler-wallet-core/src/headless/NodeHttpLib.d.ts.map b/packages/taler-wallet-core/src/headless/NodeHttpLib.d.ts.map
new file mode 100644
index 000000000..06ba7a3e1
--- /dev/null
+++ b/packages/taler-wallet-core/src/headless/NodeHttpLib.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"NodeHttpLib.d.ts","sourceRoot":"","sources":["NodeHttpLib.ts"],"names":[],"mappings":"AAkBA;;GAEG;AACH,OAAO,EAEL,kBAAkB,EAClB,kBAAkB,EAClB,YAAY,EACb,MAAM,cAAc,CAAC;AAMtB;;GAEG;AACH,qBAAa,WAAY,YAAW,kBAAkB;IACpD,OAAO,CAAC,QAAQ,CAA0B;IAC1C,OAAO,CAAC,iBAAiB,CAAQ;IAEjC;;OAEG;IACH,aAAa,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI;YAIvB,GAAG;IA2EX,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,kBAAkB,GAAG,OAAO,CAAC,YAAY,CAAC;IAIjE,QAAQ,CACZ,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,GAAG,EACT,GAAG,CAAC,EAAE,kBAAkB,GACvB,OAAO,CAAC,YAAY,CAAC;CAGzB"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/headless/NodeHttpLib.ts b/packages/taler-wallet-core/src/headless/NodeHttpLib.ts
new file mode 100644
index 000000000..d109c3b7c
--- /dev/null
+++ b/packages/taler-wallet-core/src/headless/NodeHttpLib.ts
@@ -0,0 +1,133 @@
+/*
+ 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/packages/taler-wallet-core/src/headless/helpers.ts b/packages/taler-wallet-core/src/headless/helpers.ts
new file mode 100644
index 000000000..953493299
--- /dev/null
+++ b/packages/taler-wallet-core/src/headless/helpers.ts
@@ -0,0 +1,135 @@
+/*
+ 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";
+import type { IDBFactory } from "idb-bridge/lib/idbtypes";
+
+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/packages/taler-wallet-core/src/i18n/de.po b/packages/taler-wallet-core/src/i18n/de.po
new file mode 100644
index 000000000..bb355403d
--- /dev/null
+++ b/packages/taler-wallet-core/src/i18n/de.po
@@ -0,0 +1,363 @@
+# 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/packages/taler-wallet-core/src/i18n/en-US.po b/packages/taler-wallet-core/src/i18n/en-US.po
new file mode 100644
index 000000000..4fe38d5e9
--- /dev/null
+++ b/packages/taler-wallet-core/src/i18n/en-US.po
@@ -0,0 +1,294 @@
+# 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/packages/taler-wallet-core/src/i18n/fr.po b/packages/taler-wallet-core/src/i18n/fr.po
new file mode 100644
index 000000000..67b09de1a
--- /dev/null
+++ b/packages/taler-wallet-core/src/i18n/fr.po
@@ -0,0 +1,290 @@
+# 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/packages/taler-wallet-core/src/i18n/index.ts b/packages/taler-wallet-core/src/i18n/index.ts
new file mode 100644
index 000000000..b248d2666
--- /dev/null
+++ b/packages/taler-wallet-core/src/i18n/index.ts
@@ -0,0 +1,78 @@
+/*
+ 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 "./strings";
+export { strings } from "./strings";
+
+// @ts-ignore: no type decl for this library
+import * as jedLib from "jed";
+
+export let jed: any = undefined;
+
+/**
+ * Set up jed library for internationalization,
+ * based on browser language settings.
+ */
+export function setupI18n(lang: string): any {
+ lang = lang.replace("_", "-");
+
+ if (!strings[lang]) {
+ lang = "en-US";
+ console.log(`language ${lang} not found, defaulting to english`);
+ }
+ jed = 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;
+}
diff --git a/packages/taler-wallet-core/src/i18n/it.po b/packages/taler-wallet-core/src/i18n/it.po
new file mode 100644
index 000000000..67b09de1a
--- /dev/null
+++ b/packages/taler-wallet-core/src/i18n/it.po
@@ -0,0 +1,290 @@
+# 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/packages/taler-wallet-core/src/i18n/poheader b/packages/taler-wallet-core/src/i18n/poheader
new file mode 100644
index 000000000..3ec704932
--- /dev/null
+++ b/packages/taler-wallet-core/src/i18n/poheader
@@ -0,0 +1,26 @@
+# 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/packages/taler-wallet-core/src/i18n/strings-prelude b/packages/taler-wallet-core/src/i18n/strings-prelude
new file mode 100644
index 000000000..aa6602bd4
--- /dev/null
+++ b/packages/taler-wallet-core/src/i18n/strings-prelude
@@ -0,0 +1,17 @@
+/*
+ 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/packages/taler-wallet-core/src/i18n/strings.ts b/packages/taler-wallet-core/src/i18n/strings.ts
new file mode 100644
index 000000000..748b9656a
--- /dev/null
+++ b/packages/taler-wallet-core/src/i18n/strings.ts
@@ -0,0 +1,373 @@
+/*
+ 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/packages/taler-wallet-core/src/i18n/sv.po b/packages/taler-wallet-core/src/i18n/sv.po
new file mode 100644
index 000000000..c6a739789
--- /dev/null
+++ b/packages/taler-wallet-core/src/i18n/sv.po
@@ -0,0 +1,388 @@
+# 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/packages/taler-wallet-core/src/i18n/taler-wallet-webex.pot b/packages/taler-wallet-core/src/i18n/taler-wallet-webex.pot
new file mode 100644
index 000000000..67b09de1a
--- /dev/null
+++ b/packages/taler-wallet-core/src/i18n/taler-wallet-webex.pot
@@ -0,0 +1,290 @@
+# 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/packages/taler-wallet-core/src/index.ts b/packages/taler-wallet-core/src/index.ts
new file mode 100644
index 000000000..e70fc44f6
--- /dev/null
+++ b/packages/taler-wallet-core/src/index.ts
@@ -0,0 +1,75 @@
+/*
+ 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 {
+ getDefaultNodeWallet,
+ DefaultNodeWalletArgs,
+} from "./headless/helpers";
+export { Amounts, AmountJson } from "./util/amounts";
+export { Logger } from "./util/logging";
+
+export * as talerCrypto from "./crypto/talerCrypto";
+export {
+ OperationFailedAndReportedError,
+ OperationFailedError,
+ makeErrorDetails,
+} from "./operations/errors";
+
+export * as walletTypes from "./types/walletTypes";
+
+export * as talerTypes from "./types/talerTypes";
+
+export * as walletCoreApi from "./walletCoreApiHandler";
+
+export * as taleruri from "./util/taleruri";
+
+export * as time from "./util/time";
+
+export * as codec from "./util/codec";
+
+export { NodeHttpLib } from "./headless/NodeHttpLib";
+
+export * as payto from "./util/payto";
+
+export * as testvectors from "./util/testvectors";
+
+export * as versions from "./operations/versions";
+
+export type { CryptoWorker } from "./crypto/workers/cryptoWorker";
+export type { CryptoWorkerFactory } from "./crypto/workers/cryptoApi";
+
+export * as httpLib from "./util/http";
+
+export { TalerErrorCode } from "./TalerErrorCode";
+
+export * as queryLib from "./util/query";
+
+export { CryptoImplementation } from "./crypto/workers/cryptoImplementation";
+
+export * as db from "./db";
+
+export * as promiseUtil from "./util/promiseUtils";
+
+export * as i18n from "./i18n";
+
+export * as nodeThreadWorker from "./crypto/workers/nodeThreadWorker";
+
+export * as walletNotifications from "./types/notifications";
diff --git a/packages/taler-wallet-core/src/operations/balance.d.ts.map b/packages/taler-wallet-core/src/operations/balance.d.ts.map
new file mode 100644
index 000000000..264d3139b
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/balance.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"balance.d.ts","sourceRoot":"","sources":["balance.ts"],"names":[],"mappings":"AAgBA;;GAEG;AACH,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAc9C;;GAEG;AACH,wBAAsB,4BAA4B,CAChD,EAAE,EAAE,mBAAmB,EACvB,EAAE,EAAE,iBAAiB,GACpB,OAAO,CAAC,gBAAgB,CAAC,CAqF3B;AAED;;GAEG;AACH,wBAAsB,WAAW,CAC/B,EAAE,EAAE,mBAAmB,GACtB,OAAO,CAAC,gBAAgB,CAAC,CAmB3B"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/operations/balance.ts b/packages/taler-wallet-core/src/operations/balance.ts
new file mode 100644
index 000000000..26f0aaeee
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/balance.ts
@@ -0,0 +1,153 @@
+/*
+ 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/packages/taler-wallet-core/src/operations/errors.d.ts.map b/packages/taler-wallet-core/src/operations/errors.d.ts.map
new file mode 100644
index 000000000..e5763f31a
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/errors.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["errors.ts"],"names":[],"mappings":"AAgBA;;;;GAIG;AAEH;;GAEG;AACH,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnD;;;GAGG;AACH,qBAAa,+BAAgC,SAAQ,KAAK;IACrC,cAAc,EAAE,qBAAqB;gBAArC,cAAc,EAAE,qBAAqB;CAMzD;AAED;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,KAAK;IAS1B,cAAc,EAAE,qBAAqB;IARxD,MAAM,CAAC,QAAQ,CACb,EAAE,EAAE,cAAc,EAClB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC/B,oBAAoB;gBAIJ,cAAc,EAAE,qBAAqB;CAMzD;AAED,wBAAgB,gBAAgB,CAC9B,EAAE,EAAE,cAAc,EAClB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC/B,qBAAqB,CAOvB;AAED;;;;GAIG;AACH,wBAAsB,uBAAuB,CAAC,CAAC,EAC7C,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACpB,SAAS,EAAE,CAAC,CAAC,EAAE,qBAAqB,KAAK,OAAO,CAAC,IAAI,CAAC,GACrD,OAAO,CAAC,CAAC,CAAC,CAqCZ"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/operations/errors.ts b/packages/taler-wallet-core/src/operations/errors.ts
new file mode 100644
index 000000000..198d3f8c5
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/errors.ts
@@ -0,0 +1,121 @@
+/*
+ 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/packages/taler-wallet-core/src/operations/exchanges.d.ts.map b/packages/taler-wallet-core/src/operations/exchanges.d.ts.map
new file mode 100644
index 000000000..963a271fd
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/exchanges.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"exchanges.d.ts","sourceRoot":"","sources":["exchanges.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAO9C,OAAO,EACL,cAAc,EAQf,MAAM,kBAAkB,CAAC;AA0R1B,wBAAsB,4BAA4B,CAChD,EAAE,EAAE,mBAAmB,EACvB,eAAe,EAAE,MAAM,EACvB,IAAI,EAAE,MAAM,GAAG,SAAS,GACvB,OAAO,CAAC,IAAI,CAAC,CAUf;AAsFD,wBAAsB,qBAAqB,CACzC,EAAE,EAAE,mBAAmB,EACvB,OAAO,EAAE,MAAM,EACf,QAAQ,UAAQ,GACf,OAAO,CAAC,cAAc,CAAC,CAOzB;AAoED;;GAEG;AACH,wBAAsB,gBAAgB,CACpC,EAAE,EAAE,mBAAmB,EACvB,YAAY,EAAE,cAAc,GAC3B,OAAO,CAAC;IAAE,SAAS,EAAE,OAAO,CAAC;IAAC,SAAS,EAAE,OAAO,CAAA;CAAE,CAAC,CA4BrD;AAED,wBAAsB,mBAAmB,CACvC,EAAE,EAAE,mBAAmB,EACvB,eAAe,EAAE,MAAM,EACvB,oBAAoB,EAAE,MAAM,EAAE,GAC7B,OAAO,CAAC,MAAM,CAAC,CAqBjB"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/operations/exchanges.ts b/packages/taler-wallet-core/src/operations/exchanges.ts
new file mode 100644
index 000000000..ee49fddb5
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/exchanges.ts
@@ -0,0 +1,555 @@
+/*
+ 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";
+import { URL } from "../util/url";
+
+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/packages/taler-wallet-core/src/operations/pay.d.ts.map b/packages/taler-wallet-core/src/operations/pay.d.ts.map
new file mode 100644
index 000000000..7ab4d7be6
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/pay.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"pay.d.ts","sourceRoot":"","sources":["pay.ts"],"names":[],"mappings":"AA6CA,OAAO,EACL,gBAAgB,EAEhB,gBAAgB,EAGjB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAK7C,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAY9C;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;OAEG;IACH,aAAa,EAAE,UAAU,CAAC;IAE1B;;OAEG;IACH,QAAQ,EAAE,MAAM,EAAE,CAAC;IAEnB;;OAEG;IACH,iBAAiB,EAAE,UAAU,EAAE,CAAC;IAEhC;;OAE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AkB,CACtC,EAAE,EAAE,mBAAmB,EACvB,UAAU,EAAE,MAAM,EAClB,QAAQ,UAAQ,GACf,OAAO,CAAC,IAAI,CAAC,CAOf;AAiCD,wBAAsB,cAAc,CAClC,EAAE,EAAE,mBAAmB,EACvB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,IAAI,CAAC,CAsBf"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/operations/pay.ts b/packages/taler-wallet-core/src/operations/pay.ts
new file mode 100644
index 000000000..f23e326f8
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/pay.ts
@@ -0,0 +1,1148 @@
+/*
+ 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";
+import { URL } from "../util/url";
+
+/**
+ * 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/packages/taler-wallet-core/src/operations/pending.d.ts.map b/packages/taler-wallet-core/src/operations/pending.d.ts.map
new file mode 100644
index 000000000..08897f538
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/pending.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"pending.d.ts","sourceRoot":"","sources":["pending.ts"],"names":[],"mappings":"AAyBA,OAAO,EACL,yBAAyB,EAI1B,MAAM,kBAAkB,CAAC;AAS1B,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AA6X9C,wBAAsB,oBAAoB,CACxC,EAAE,EAAE,mBAAmB,EACvB,EAAE,OAAe,EAAE;;CAAK,GACvB,OAAO,CAAC,yBAAyB,CAAC,CAkCpC"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/operations/pending.ts b/packages/taler-wallet-core/src/operations/pending.ts
new file mode 100644
index 000000000..acad5e634
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/pending.ts
@@ -0,0 +1,458 @@
+/*
+ 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/packages/taler-wallet-core/src/operations/recoup.d.ts.map b/packages/taler-wallet-core/src/operations/recoup.d.ts.map
new file mode 100644
index 000000000..c5c9254d1
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/recoup.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"recoup.d.ts","sourceRoot":"","sources":["recoup.ts"],"names":[],"mappings":"AAgBA;;;;;GAKG;AAEH;;GAEG;AACH,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAqB9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAyPlD,wBAAsB,kBAAkB,CACtC,EAAE,EAAE,mBAAmB,EACvB,aAAa,EAAE,MAAM,EACrB,QAAQ,UAAQ,GACf,OAAO,CAAC,IAAI,CAAC,CASf;AA0BD,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,mBAAmB,EACvB,EAAE,EAAE,iBAAiB,EACrB,QAAQ,EAAE,MAAM,EAAE,GACjB,OAAO,CAAC,MAAM,CAAC,CAmCjB"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/operations/recoup.ts b/packages/taler-wallet-core/src/operations/recoup.ts
new file mode 100644
index 000000000..cc91ab0e9
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/recoup.ts
@@ -0,0 +1,412 @@
+/*
+ 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";
+import { URL } from "../util/url";
+
+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/packages/taler-wallet-core/src/operations/refresh.d.ts.map b/packages/taler-wallet-core/src/operations/refresh.d.ts.map
new file mode 100644
index 000000000..01cbe7458
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/refresh.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"refresh.d.ts","sourceRoot":"","sources":["refresh.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAW,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EACL,kBAAkB,EAUnB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAI9C,OAAO,EAEL,aAAa,EACb,aAAa,EACb,cAAc,EACf,MAAM,sBAAsB,CAAC;AAc9B;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,kBAAkB,EAAE,EAC5B,cAAc,EAAE,kBAAkB,EAClC,UAAU,EAAE,UAAU,GACrB,UAAU,CAiBZ;AA0WD,wBAAsB,mBAAmB,CACvC,EAAE,EAAE,mBAAmB,EACvB,cAAc,EAAE,MAAM,EACtB,QAAQ,UAAQ,GACf,OAAO,CAAC,IAAI,CAAC,CASf;AAyED;;GAEG;AACH,wBAAsB,kBAAkB,CACtC,EAAE,EAAE,mBAAmB,EACvB,EAAE,EAAE,iBAAiB,EACrB,WAAW,EAAE,aAAa,EAAE,EAC5B,MAAM,EAAE,aAAa,GACpB,OAAO,CAAC,cAAc,CAAC,CA8BzB"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/operations/refresh.ts b/packages/taler-wallet-core/src/operations/refresh.ts
new file mode 100644
index 000000000..646bc2edf
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/refresh.ts
@@ -0,0 +1,573 @@
+/*
+ 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";
+import { URL } from "../util/url";
+
+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/packages/taler-wallet-core/src/operations/refund.d.ts.map b/packages/taler-wallet-core/src/operations/refund.d.ts.map
new file mode 100644
index 000000000..77efa7cae
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/refund.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"refund.d.ts","sourceRoot":"","sources":["refund.ts"],"names":[],"mappings":"AAgBA;;;;GAIG;AAEH;;GAEG;AACH,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AA0S9C;;;GAGG;AACH,wBAAsB,WAAW,CAC/B,EAAE,EAAE,mBAAmB,EACvB,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC;IAAE,iBAAiB,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAAC,CA2B5D;AAED,wBAAsB,0BAA0B,CAC9C,EAAE,EAAE,mBAAmB,EACvB,UAAU,EAAE,MAAM,EAClB,QAAQ,UAAQ,GACf,OAAO,CAAC,IAAI,CAAC,CAOf"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/operations/refund.ts b/packages/taler-wallet-core/src/operations/refund.ts
new file mode 100644
index 000000000..9792d2268
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/refund.ts
@@ -0,0 +1,438 @@
+/*
+ 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";
+import { URL } from "../util/url";
+
+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/packages/taler-wallet-core/src/operations/reserves.d.ts.map b/packages/taler-wallet-core/src/operations/reserves.d.ts.map
new file mode 100644
index 000000000..33d646ba5
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/reserves.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"reserves.d.ts","sourceRoot":"","sources":["reserves.ts"],"names":[],"mappings":"AAgBA,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EAErB,wBAAwB,EACzB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AA+C9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAyBlD;;;;;GAKG;AACH,wBAAsB,aAAa,CACjC,EAAE,EAAE,mBAAmB,EACvB,GAAG,EAAE,oBAAoB,GACxB,OAAO,CAAC,qBAAqB,CAAC,CA+JhC;AAED;;GAEG;AACH,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,mBAAmB,EACvB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,IAAI,CAAC,CAoBf;AAED;;;;;;GAMG;AACH,wBAAsB,cAAc,CAClC,EAAE,EAAE,mBAAmB,EACvB,UAAU,EAAE,MAAM,EAClB,QAAQ,UAAQ,GACf,OAAO,CAAC,IAAI,CAAC,CASf;AA+CD,wBAAsB,wBAAwB,CAC5C,EAAE,EAAE,mBAAmB,EACvB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,IAAI,CAAC,CAOf;AA8ZD,wBAAsB,0BAA0B,CAC9C,EAAE,EAAE,mBAAmB,EACvB,gBAAgB,EAAE,MAAM,EACxB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC,wBAAwB,CAAC,CAqBnC;AAED;;GAEG;AACH,wBAAsB,mBAAmB,CACvC,EAAE,EAAE,iBAAiB,EACrB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,EAAE,CAAC,CAuBnB"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/operations/reserves.ts b/packages/taler-wallet-core/src/operations/reserves.ts
new file mode 100644
index 000000000..58095affd
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/reserves.ts
@@ -0,0 +1,841 @@
+/*
+ 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";
+import { URL } from "../util/url";
+
+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/packages/taler-wallet-core/src/operations/state.d.ts.map b/packages/taler-wallet-core/src/operations/state.d.ts.map
new file mode 100644
index 000000000..275197839
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/state.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"state.d.ts","sourceRoot":"","sources":["state.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACvE,OAAO,EAAE,SAAS,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAC7E,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAEtE,OAAO,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAC7D,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAEzC,aAAK,oBAAoB,GAAG,CAAC,CAAC,EAAE,kBAAkB,KAAK,IAAI,CAAC;AAI5D,qBAAa,mBAAmB;IAerB,EAAE,EAAE,QAAQ;IACZ,IAAI,EAAE,kBAAkB;IAfjC,aAAa,EAAE;QAAE,CAAC,cAAc,EAAE,MAAM,GAAG,aAAa,CAAA;KAAE,CAAM;IAChE,kBAAkB,EAAE,cAAc,CAAC,IAAI,CAAC,CAAwB;IAChE,gBAAgB,EAAE,cAAc,CAAC,IAAI,CAAC,CAAwB;IAC9D,cAAc,EAAE,iBAAiB,CAC/B,yBAAyB,CAC1B,CAA2B;IAC5B,cAAc,EAAE,iBAAiB,CAAC,gBAAgB,CAAC,CAA2B;IAC9E,kBAAkB,EAAE,cAAc,CAAC,IAAI,CAAC,CAAwB;IAChE,iBAAiB,EAAE,cAAc,CAAC,IAAI,CAAC,CAAwB;IAC/D,SAAS,EAAE,SAAS,CAAC;IAErB,SAAS,EAAE,oBAAoB,EAAE,CAAM;gBAG9B,EAAE,EAAE,QAAQ,EACZ,IAAI,EAAE,kBAAkB,EAC/B,mBAAmB,EAAE,mBAAmB;IAKnC,MAAM,CAAC,CAAC,EAAE,kBAAkB,GAAG,IAAI;IAU1C,uBAAuB,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,kBAAkB,KAAK,IAAI,GAAG,IAAI;CAGlE"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/operations/state.ts b/packages/taler-wallet-core/src/operations/state.ts
new file mode 100644
index 000000000..cfec85d0f
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/state.ts
@@ -0,0 +1,65 @@
+/*
+ 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/packages/taler-wallet-core/src/operations/testing.d.ts.map b/packages/taler-wallet-core/src/operations/testing.d.ts.map
new file mode 100644
index 000000000..d7b3ceaec
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/testing.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["testing.ts"],"names":[],"mappings":"AAwBA,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAuC9C,wBAAsB,mBAAmB,CACvC,EAAE,EAAE,mBAAmB,EACvB,MAAM,SAAiB,EACvB,WAAW,SAAiC,EAC5C,eAAe,SAAqC,GACnD,OAAO,CAAC,IAAI,CAAC,CAuBf"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/operations/testing.ts b/packages/taler-wallet-core/src/operations/testing.ts
new file mode 100644
index 000000000..71cee1f3a
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/testing.ts
@@ -0,0 +1,156 @@
+/*
+ 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 { Logger } from "../util/logging";
+import {
+ HttpRequestLibrary,
+ readSuccessResponseJsonOrThrow,
+ checkSuccessResponseOrThrow,
+} from "../util/http";
+import { codecForAny } from "../util/codec";
+import { AmountString } from "../types/talerTypes";
+import { InternalWalletState } from "./state";
+import { createTalerWithdrawReserve } from "./reserves";
+import { URL } from "../util/url";
+
+const logger = new Logger("operations/testing.ts");
+
+interface BankUser {
+ username: string;
+ password: string;
+}
+
+interface BankWithdrawalResponse {
+ taler_withdraw_uri: string;
+ withdrawal_id: string;
+}
+
+/**
+ * Generate a random alphanumeric ID. Does *not* use cryptographically
+ * secure randomness.
+ */
+function makeId(length: number): string {
+ let result = "";
+ const characters =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
+ for (let i = 0; i < length; i++) {
+ result += characters.charAt(Math.floor(Math.random() * characters.length));
+ }
+ return result;
+}
+
+/**
+ * Helper function to generate the "Authorization" HTTP header.
+ */
+function makeAuth(username: string, password: string): string {
+ const auth = `${username}:${password}`;
+ const authEncoded: string = Buffer.from(auth).toString("base64");
+ return `Basic ${authEncoded}`;
+}
+
+export async function withdrawTestBalance(
+ ws: InternalWalletState,
+ amount = "TESTKUDOS:10",
+ bankBaseUrl = "https://bank.test.taler.net/",
+ exchangeBaseUrl = "https://exchange.test.taler.net/",
+): Promise<void> {
+ const bankUser = await registerRandomBankUser(ws.http, bankBaseUrl);
+ logger.trace(`Registered bank user ${JSON.stringify(bankUser)}`);
+
+ const wresp = await createBankWithdrawalUri(
+ ws.http,
+ bankBaseUrl,
+ bankUser,
+ amount,
+ );
+
+ await createTalerWithdrawReserve(
+ ws,
+ wresp.taler_withdraw_uri,
+ exchangeBaseUrl,
+ );
+
+ await confirmBankWithdrawalUri(
+ ws.http,
+ bankBaseUrl,
+ bankUser,
+ wresp.withdrawal_id,
+ );
+}
+
+async function createBankWithdrawalUri(
+ http: HttpRequestLibrary,
+ bankBaseUrl: string,
+ bankUser: BankUser,
+ amount: AmountString,
+): Promise<BankWithdrawalResponse> {
+ const reqUrl = new URL(
+ `accounts/${bankUser.username}/withdrawals`,
+ bankBaseUrl,
+ ).href;
+ const resp = await http.postJson(
+ reqUrl,
+ {
+ amount,
+ },
+ {
+ headers: {
+ Authorization: makeAuth(bankUser.username, bankUser.password),
+ },
+ },
+ );
+ const respJson = await readSuccessResponseJsonOrThrow(resp, codecForAny);
+ return respJson;
+}
+
+async function confirmBankWithdrawalUri(
+ http: HttpRequestLibrary,
+ bankBaseUrl: string,
+ bankUser: BankUser,
+ withdrawalId: string,
+): Promise<void> {
+ const reqUrl = new URL(
+ `accounts/${bankUser.username}/withdrawals/${withdrawalId}/confirm`,
+ bankBaseUrl,
+ ).href;
+ const resp = await http.postJson(
+ reqUrl,
+ {},
+ {
+ headers: {
+ Authorization: makeAuth(bankUser.username, bankUser.password),
+ },
+ },
+ );
+ await readSuccessResponseJsonOrThrow(resp, codecForAny);
+ return;
+}
+
+async function registerRandomBankUser(
+ http: HttpRequestLibrary,
+ bankBaseUrl: string,
+): Promise<BankUser> {
+ const reqUrl = new URL("testing/register", bankBaseUrl).href;
+ const randId = makeId(8);
+ const bankUser: BankUser = {
+ username: `testuser-${randId}`,
+ password: `testpw-${randId}`,
+ };
+
+ const resp = await http.postJson(reqUrl, bankUser);
+ await checkSuccessResponseOrThrow(resp);
+ return bankUser;
+}
diff --git a/packages/taler-wallet-core/src/operations/tip.d.ts.map b/packages/taler-wallet-core/src/operations/tip.d.ts.map
new file mode 100644
index 000000000..8d8a72fb8
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/tip.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"tip.d.ts","sourceRoot":"","sources":["tip.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAE9C,OAAO,EAAE,SAAS,EAAyB,MAAM,sBAAsB,CAAC;AA8BxE,wBAAsB,YAAY,CAChC,EAAE,EAAE,mBAAmB,EACvB,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC,SAAS,CAAC,CAgFpB;AAuBD,wBAAsB,UAAU,CAC9B,EAAE,EAAE,mBAAmB,EACvB,KAAK,EAAE,MAAM,EACb,QAAQ,UAAQ,GACf,OAAO,CAAC,IAAI,CAAC,CAOf;AAkKD,wBAAsB,SAAS,CAC7B,EAAE,EAAE,mBAAmB,EACvB,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC,CAYf"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/operations/tip.ts b/packages/taler-wallet-core/src/operations/tip.ts
new file mode 100644
index 000000000..d6768bdb6
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/tip.ts
@@ -0,0 +1,343 @@
+/*
+ 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";
+import { URL } from "../util/url";
+
+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/packages/taler-wallet-core/src/operations/transactions.d.ts.map b/packages/taler-wallet-core/src/operations/transactions.d.ts.map
new file mode 100644
index 000000000..5a462e4d6
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/transactions.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"transactions.d.ts","sourceRoot":"","sources":["transactions.ts"],"names":[],"mappings":"AAgBA;;GAEG;AACH,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAO9C,OAAO,EACL,mBAAmB,EACnB,oBAAoB,EAMrB,MAAM,uBAAuB,CAAC;AAoC/B;;GAEG;AACH,wBAAsB,eAAe,CACnC,EAAE,EAAE,mBAAmB,EACvB,mBAAmB,CAAC,EAAE,mBAAmB,GACxC,OAAO,CAAC,oBAAoB,CAAC,CAuN/B"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/operations/transactions.ts b/packages/taler-wallet-core/src/operations/transactions.ts
new file mode 100644
index 000000000..2d66b5e9d
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/transactions.ts
@@ -0,0 +1,288 @@
+/*
+ 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/packages/taler-wallet-core/src/operations/versions.d.ts.map b/packages/taler-wallet-core/src/operations/versions.d.ts.map
new file mode 100644
index 000000000..15ba8d27e
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/versions.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"versions.d.ts","sourceRoot":"","sources":["versions.ts"],"names":[],"mappings":"AAgBA;;;;GAIG;AACH,eAAO,MAAM,gCAAgC,UAAU,CAAC;AAExD;;;;GAIG;AACH,eAAO,MAAM,gCAAgC,UAAU,CAAC;AAExD;;;;;;GAMG;AACH,eAAO,MAAM,mCAAmC,MAAM,CAAC"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/operations/versions.ts b/packages/taler-wallet-core/src/operations/versions.ts
new file mode 100644
index 000000000..31c4921c6
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/versions.ts
@@ -0,0 +1,38 @@
+/*
+ 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/packages/taler-wallet-core/src/operations/withdraw-test.ts b/packages/taler-wallet-core/src/operations/withdraw-test.ts
new file mode 100644
index 000000000..24cb6f4b1
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/withdraw-test.ts
@@ -0,0 +1,332 @@
+/*
+ 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/packages/taler-wallet-core/src/operations/withdraw.d.ts.map b/packages/taler-wallet-core/src/operations/withdraw.d.ts.map
new file mode 100644
index 000000000..51eeb1888
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/withdraw.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"withdraw.d.ts","sourceRoot":"","sources":["withdraw.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,UAAU,EAAW,MAAM,iBAAiB,CAAC;AACtD,OAAO,EACL,kBAAkB,EAQlB,yBAAyB,EAGzB,mBAAmB,EACpB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,mBAAmB,EACnB,uBAAuB,EAGxB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAGL,uBAAuB,EACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAgC9C;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,eAAe,EAAE,UAAU,EAC3B,MAAM,EAAE,kBAAkB,EAAE,GAC3B,yBAAyB,CAiD3B;AAED;;;GAGG;AACH,wBAAsB,qBAAqB,CACzC,EAAE,EAAE,mBAAmB,EACvB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC,mBAAmB,CAAC,CAyB9B;AA2QD,wBAAgB,yBAAyB,CACvC,GAAG,EAAE,yBAAyB,GAC7B,mBAAmB,CAWrB;AAED;;;;;;GAMG;AACH,wBAAsB,sBAAsB,CAC1C,EAAE,EAAE,mBAAmB,EACvB,eAAe,EAAE,MAAM,EACvB,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,yBAAyB,CAAC,CA8CpC;AAyBD,wBAAsB,oBAAoB,CACxC,EAAE,EAAE,mBAAmB,EACvB,iBAAiB,EAAE,MAAM,EACzB,QAAQ,UAAQ,GACf,OAAO,CAAC,IAAI,CAAC,CAOf;AAsED,wBAAsB,yBAAyB,CAC7C,EAAE,EAAE,mBAAmB,EACvB,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,uBAAuB,CAAC,CA8FlC;AAED,wBAAsB,0BAA0B,CAC9C,EAAE,EAAE,mBAAmB,EACvB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC,uBAAuB,CAAC,CA2ClC"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/operations/withdraw.ts b/packages/taler-wallet-core/src/operations/withdraw.ts
new file mode 100644
index 000000000..3b0aa0095
--- /dev/null
+++ b/packages/taler-wallet-core/src/operations/withdraw.ts
@@ -0,0 +1,759 @@
+/*
+ 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";
+import { URL } from "../util/url";
+
+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/packages/taler-wallet-core/src/types/ReserveStatus.d.ts.map b/packages/taler-wallet-core/src/types/ReserveStatus.d.ts.map
new file mode 100644
index 000000000..6b84dde85
--- /dev/null
+++ b/packages/taler-wallet-core/src/types/ReserveStatus.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"ReserveStatus.d.ts","sourceRoot":"","sources":["ReserveStatus.ts"],"names":[],"mappings":"AAgBA;;GAEG;AAEH;;GAEG;AACH,OAAO,EAIL,KAAK,EACN,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EACL,kBAAkB,EAEnB,MAAM,sBAAsB,CAAC;AAE9B;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC5B;;OAEG;IACH,OAAO,EAAE,YAAY,CAAC;IAEtB;;OAEG;IACH,OAAO,EAAE,kBAAkB,EAAE,CAAC;CAC/B;AAED,eAAO,MAAM,qBAAqB,QAAO,KAAK,CAAC,aAAa,CAIjC,CAAC"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/types/ReserveStatus.ts b/packages/taler-wallet-core/src/types/ReserveStatus.ts
new file mode 100644
index 000000000..18601b9a7
--- /dev/null
+++ b/packages/taler-wallet-core/src/types/ReserveStatus.ts
@@ -0,0 +1,57 @@
+/*
+ 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/packages/taler-wallet-core/src/types/ReserveTransaction.d.ts.map b/packages/taler-wallet-core/src/types/ReserveTransaction.d.ts.map
new file mode 100644
index 000000000..c4672bc45
--- /dev/null
+++ b/packages/taler-wallet-core/src/types/ReserveTransaction.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"ReserveTransaction.d.ts","sourceRoot":"","sources":["ReserveTransaction.ts"],"names":[],"mappings":"AAgBA;;GAEG;AAEH;;GAEG;AACH,OAAO,EAKL,KAAK,EACN,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,YAAY,EACZ,YAAY,EACZ,oBAAoB,EACpB,oBAAoB,EACpB,mBAAmB,EACpB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,SAAS,EAAqB,MAAM,cAAc,CAAC;AAE5D,0BAAkB,sBAAsB;IACtC,QAAQ,aAAa;IACrB,MAAM,WAAW;IACjB,MAAM,WAAW;IACjB,OAAO,YAAY;CACpB;AAED,MAAM,WAAW,0B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Y,kBAAkB,GAC1B,0BAA0B,GAC1B,wBAAwB,GACxB,yBAAyB,GACzB,wBAAwB,CAAC;AAE7B,eAAO,MAAM,kCAAkC,QAAO,KAAK,CACzD,0BAA0B,CASY,CAAC;AAEzC,eAAO,MAAM,gCAAgC,QAAO,KAAK,CACvD,wBAAwB,CAQY,CAAC;AAEvC,eAAO,MAAM,iCAAiC,QAAO,KAAK,CACxD,yBAAyB,CAWY,CAAC;AAExC,eAAO,MAAM,gCAAgC,QAAO,KAAK,CACvD,wBAAwB,CASY,CAAC;AAEvC,eAAO,MAAM,0BAA0B,QAAO,KAAK,CAAC,kBAAkB,CAmBlB,CAAC"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/types/ReserveTransaction.ts b/packages/taler-wallet-core/src/types/ReserveTransaction.ts
new file mode 100644
index 000000000..bdd9b0f93
--- /dev/null
+++ b/packages/taler-wallet-core/src/types/ReserveTransaction.ts
@@ -0,0 +1,250 @@
+/*
+ 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/packages/taler-wallet-core/src/types/dbTypes.d.ts.map b/packages/taler-wallet-core/src/types/dbTypes.d.ts.map
new file mode 100644
index 000000000..7b89c4de4
--- /dev/null
+++ b/packages/taler-wallet-core/src/types/dbTypes.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"dbTypes.d.ts","sourceRoot":"","sources":["dbTypes.ts"],"names":[],"mappings":"AAgBA;;;;GAIG;AAEH;;GAEG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EACL,OAAO,EACP,qBAAqB,EACrB,WAAW,EACX,mBAAmB,EACnB,YAAY,EACZ,OAAO,EACR,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACrE,OAAO,EACL,kBAAkB,EAClB,wBAAwB,EACxB,0BAA0B,EAC1B,yBAAyB,EACzB,wBAAwB,EACzB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE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allet-core/src/types/dbTypes.ts
new file mode 100644
index 000000000..3e1fdfe25
--- /dev/null
+++ b/packages/taler-wallet-core/src/types/dbTypes.ts
@@ -0,0 +1,1819 @@
+/*
+ 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";
+import { idbtypes } from "idb-bridge";
+
+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 */
+
+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 idbtypes.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" });
+ }
+}
+
+/**
+ * The stores and indices for the wallet database.
+ */
+
+export const Stores = {
+ coins: new CoinsStore(),
+ coinsReturns: new Store<CoinsReturnRecord>("coinsReturns", {
+ keyPath: "contractTermsHash",
+ }),
+ config: new ConfigStore(),
+ currencies: new CurrenciesStore(),
+ denominations: new DenominationsStore(),
+ exchanges: new ExchangesStore(),
+ proposals: new ProposalsStore(),
+ refreshGroups: new Store<RefreshGroupRecord>("refreshGroups", {
+ keyPath: "refreshGroupId",
+ }),
+ recoupGroups: new Store<RecoupGroupRecord>("recoupGroups", {
+ keyPath: "recoupGroupId",
+ }),
+ reserves: new ReservesStore(),
+ reserveHistory: new ReserveHistoryStore(),
+ purchases: new PurchasesStore(),
+ tips: new TipsStore(),
+ senderWires: new SenderWiresStore(),
+ withdrawalGroups: new WithdrawalGroupsStore(),
+ planchets: new PlanchetsStore(),
+ bankWithdrawUris: new BankWithdrawUrisStore(),
+ refundEvents: new RefundEventsStore(),
+ payEvents: new PayEventsStore(),
+ reserveUpdatedEvents: new ReserveUpdatedEventsStore(),
+ exchangeUpdatedEvents: new ExchangeUpdatedEventsStore(),
+ walletImports: new WalletImportsStore(),
+};
+
+/* tslint:enable:completed-docs */
diff --git a/packages/taler-wallet-core/src/types/notifications.d.ts.map b/packages/taler-wallet-core/src/types/notifications.d.ts.map
new file mode 100644
index 000000000..f1b3318d5
--- /dev/null
+++ b/packages/taler-wallet-core/src/types/notifications.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"notifications.d.ts","sourceRoot":"","sources":["notifications.ts"],"names":[],"mappings":"AAgBA;;;GAGG;AAEH;;GAEG;AACH,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAE7C,0BAAkB,gBAAgB;IAChC,aAAa,mBAAmB;IAChC,gBAAgB,sBAAsB;IACtC,kBAAkB,wBAAwB;IAC1C,gBAAgB,sBAAsB;IACtC,aAAa,mBAAmB;IAChC,cAAc,oBAAoB;IAClC,eAAe,qBAAqB;IACpC,aAAa,mBAAmB;IAChC,cAAc,oBAA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,CAAC;CAClD;AAED,MAAM,WAAW,2BAA2B;IAC1C,IAAI,EAAE,gBAAgB,CAAC,eAAe,CAAC;CACxC;AAED,MAAM,WAAW,qCAAqC;IACpD,IAAI,EAAE,gBAAgB,CAAC,yBAAyB,CAAC;CAClD;AAED,oBAAY,kBAAkB,GAC1B,kCAAkC,GAClC,iCAAiC,GACjC,kCAAkC,GAClC,iCAAiC,GACjC,sCAAsC,GACtC,qCAAqC,GACrC,kCAAkC,GAClC,6BAA6B,GAC7B,6BAA6B,GAC7B,4BAA4B,GAC5B,8BAA8B,GAC9B,4BAA4B,GAC5B,yBAAyB,GACzB,0BAA0B,GAC1B,yBAAyB,GACzB,2BAA2B,GAC3B,0BAA0B,GAC1B,0BAA0B,GAC1B,0BAA0B,GAC1B,0BAA0B,GAC1B,4BAA4B,GAC5B,mCAAmC,GACnC,2BAA2B,GAC3B,yBAAyB,GACzB,0BAA0B,GAC1B,yBAAyB,GACzB,kCAAkC,GAClC,yBAAyB,GACzB,gCAAgC,GAChC,yBAAyB,GACzB,qCAAqC,GACrC,2BAA2B,GAC3B,qCAAqC,GACrC,8BAA8B,CAAC"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/types/notifications.ts b/packages/taler-wallet-core/src/types/notifications.ts
new file mode 100644
index 000000000..945b86eea
--- /dev/null
+++ b/packages/taler-wallet-core/src/types/notifications.ts
@@ -0,0 +1,255 @@
+/*
+ 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/packages/taler-wallet-core/src/types/pending.d.ts.map b/packages/taler-wallet-core/src/types/pending.d.ts.map
new file mode 100644
index 000000000..2f88198fa
--- /dev/null
+++ b/packages/taler-wallet-core/src/types/pending.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"pending.d.ts","sourceRoot":"","sources":["pending.ts"],"names":[],"mappings":"AAgBA;;GAEG;AAEH;;GAEG;AACH,OAAO,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACxE,OAAO,EAAE,gBAAgB,EAAE,SAAS,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAC7E,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAEnD,0BAAkB,oBAAoB;IACpC,GAAG,QAAQ;IACX,cAAc,oBAAoB;IAClC,GAAG,QAAQ;IACX,cAAc,oBAAoB;IAClC,gBAAgB,sBAAsB;IACtC,OAAO,YAAY;IACnB,OAAO,YAAY;IACnB,MAAM,WAAW;IACjB,WAAW,iBAAiB;IAC5B,SAAS,eAAe;IACxB,SAAS,eAAe;IACxB,QAAQ,aAAa;CACtB;AAED;;GAEG;AACH,oBAAY,oBAAoB,GAAG,0BAA0B,GAC3D,CACI,mBAAmB,GACnB,8BAA8B,GAC9B,mBAAmB,GACnB,8BAA8B,GAC9B,gCAAgC,GAChC,uBAAuB,GACvB,2BAA2B,GAC3B,uBAAuB,GACvB,yBAAyB,GACzB,yBAAyB,GACzB,wBAAwB,GACxB,sBAAsB,CACzB,CAAC;AAEJ;;GAEG;AACH,MAAM,WAAW,8BAA8B;IAC7C,IAAI,EAAE,oBAAoB,CAAC,cAAc,CAAC;IAC1C,KAAK,EAAE,4BAA4B,CAAC;IACpC,MAAM,EAAE,MAAM,CAAC;IACf,eAAe,EAAE,MAAM,CAAC;IACxB,SAAS,EAAE,qBAAqB,GAAG,SAAS,CAAC;CAC9C;AA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iB,EAAE,MAAM,CAAC;IAC1B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,aAAa,EAAE,MAAM,CAAC;CACvB;AAED;;GAEG;AACH,MAAM,WAAW,0BAA0B;IACzC;;OAEG;IACH,IAAI,EAAE,oBAAoB,CAAC;IAE3B;;;OAGG;IACH,aAAa,EAAE,OAAO,CAAC;CACxB;AAED;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACxC;;OAEG;IACH,iBAAiB,EAAE,oBAAoB,EAAE,CAAC;IAE1C;;OAEG;IACH,aAAa,EAAE,gBAAgB,CAAC;IAEhC;;OAEG;IACH,cAAc,EAAE,QAAQ,CAAC;IAEzB;;;OAGG;IACH,OAAO,EAAE,OAAO,CAAC;CAClB"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/types/pending.ts b/packages/taler-wallet-core/src/types/pending.ts
new file mode 100644
index 000000000..85f7585c5
--- /dev/null
+++ b/packages/taler-wallet-core/src/types/pending.ts
@@ -0,0 +1,258 @@
+/*
+ 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/packages/taler-wallet-core/src/types/schemacore.ts b/packages/taler-wallet-core/src/types/schemacore.ts
new file mode 100644
index 000000000..820f68d18
--- /dev/null
+++ b/packages/taler-wallet-core/src/types/schemacore.ts
@@ -0,0 +1,58 @@
+/*
+ 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/packages/taler-wallet-core/src/types/talerTypes.d.ts.map b/packages/taler-wallet-core/src/types/talerTypes.d.ts.map
new file mode 100644
index 000000000..0419ea14f
--- /dev/null
+++ b/packages/taler-wallet-core/src/types/talerTypes.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"talerTypes.d.ts","sourceRoot":"","sources":["talerTypes.ts"],"names":[],"mappings":"AAgBA;;;;;;;GAOG;AAEH;;GAEG;AAEH,OAAO,EASL,KAAK,EAIN,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,SAAS,EAET,QAAQ,EAET,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEjD;;GAEG;AACH,qBAAa,YAAY;IACvB;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;IAElB;;OAEG;IACH,YAAY,EAAE,MAAM,CAAC;IAErB;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;OAEG;IACH,UAAU,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,WAAW,EAAE,SAAS,CAAC;IAEvB;;OAEG;IACH,qBAAqB,EAAE,SAAS,CAAC;IAEjC;;;OAGG;IACH,kBAAkB,EAAE,SAAS,CAAC;IAE9B;;;OAGG;I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,CAAC"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/types/talerTypes.ts b/packages/taler-wallet-core/src/types/talerTypes.ts
new file mode 100644
index 000000000..acebbda95
--- /dev/null
+++ b/packages/taler-wallet-core/src/types/talerTypes.ts
@@ -0,0 +1,1272 @@
+/*
+ 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/packages/taler-wallet-core/src/types/transactions.d.ts.map b/packages/taler-wallet-core/src/types/transactions.d.ts.map
new file mode 100644
index 000000000..95e19a21c
--- /dev/null
+++ b/packages/taler-wallet-core/src/types/transactions.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"transactions.d.ts","sourceRoot":"","sources":["transactions.ts"],"names":[],"mappings":"AAgBA;;;;;GAKG;AAEH;;GAEG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACrD,OAAO,EAAE,KAAK,EAAyD,MAAM,eAAe,CAAC;AAE7F,MAAM,WAAW,mBAAmB;IAClC;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,oBAAoB;IAKnC,YAAY,EAAE,WAAW,EAAE,CAAC;CAC7B;AAED,UAAU,gBAAgB;IACxB;;;OAGG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,OAAO,CAAC,EAAE,GAAG,CAAC;CACf;AAED,MAAM,WAAW,iBAAiB;IAGhC,aAAa,EAAE,MAAM,CAAC;IAGtB,IAAI,EAAE,eAAe,CAAC;IAGtB,SAAS,EAAE,SAAS,CAAC;IAKrB,OAAO,EAAE,OAAO,CAAC;IAGjB,SAAS,EAAE,YAAY,CAAC;IAGxB,eAAe,EAAE,YAAY,CAAC;IAE9B,KAAK,CAAC,EAAE,gBAAgB,CAAC;CAC1B;AAED,oBAAY,WAAW,GACnB,qBAAqB,GACrB,kBAAkB,GAClB,iBAAiB,GACjB,cAAc,GACd,kBAAkB,CAAC;AAEvB,0BAAkB,eAAe;IAC/B,UAAU,eAAe;IACzB,OAAO,YAAY;IACnB,MAAM,WAAW;IACjB,OAAO,YAAY;IACnB,GAAG,QAAQ;CACZ;AAED,0BAAkB,cAAc;IAC9B,uBAAuB,+BAA+B;IACtD,cAAc,oBAAoB;CACnC;AAED,oBAAY,iBAAiB,GACzB,kC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;IAE9C;;OAEG;IACH,QAAQ,EAAE,OAAO,EAAE,GAAG,SAAS,CAAC;IAEhC;;OAEG;IACH,cAAc,EAAE,MAAM,CAAC;CACxB;AAED,UAAU,iBAAkB,SAAQ,iBAAiB;IACnD,IAAI,EAAE,eAAe,CAAC,MAAM,CAAC;IAG7B,qBAAqB,EAAE,MAAM,CAAC;IAG9B,IAAI,EAAE,gBAAgB,CAAC;IAGvB,aAAa,EAAE,YAAY,CAAC;IAG5B,SAAS,EAAE,YAAY,CAAC;IAGxB,eAAe,EAAE,YAAY,CAAC;CAC/B;AAED,UAAU,cAAe,SAAQ,iBAAiB;IAChD,IAAI,EAAE,eAAe,CAAC,GAAG,CAAC;IAG1B,OAAO,EAAE,OAAO,CAAC;IAGjB,QAAQ,EAAE,OAAO,CAAC;IAGlB,eAAe,EAAE,MAAM,CAAC;IAGxB,QAAQ,EAAE,GAAG,CAAC;IAGd,SAAS,EAAE,YAAY,CAAC;IAGxB,eAAe,EAAE,YAAY,CAAC;CAC/B;AAKD,UAAU,kBAAmB,SAAQ,iBAAiB;IACpD,IAAI,EAAE,eAAe,CAAC,OAAO,CAAC;IAG9B,eAAe,EAAE,MAAM,CAAC;IAGxB,SAAS,EAAE,YAAY,CAAC;IAGxB,eAAe,EAAE,YAAY,CAAC;CAC/B;AAGD,eAAO,MAAM,2BAA2B,QAAO,KAAK,CAAC,mBAAmB,CAIvC,CAAC"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/types/transactions.ts b/packages/taler-wallet-core/src/types/transactions.ts
new file mode 100644
index 000000000..de378f51a
--- /dev/null
+++ b/packages/taler-wallet-core/src/types/transactions.ts
@@ -0,0 +1,314 @@
+/*
+ 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");
diff --git a/packages/taler-wallet-core/src/types/types-test.ts b/packages/taler-wallet-core/src/types/types-test.ts
new file mode 100644
index 000000000..afdc01844
--- /dev/null
+++ b/packages/taler-wallet-core/src/types/types-test.ts
@@ -0,0 +1,55 @@
+/*
+ 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/packages/taler-wallet-core/src/types/walletTypes.d.ts.map b/packages/taler-wallet-core/src/types/walletTypes.d.ts.map
new file mode 100644
index 000000000..d802110fd
--- /dev/null
+++ b/packages/taler-wallet-core/src/types/walletTypes.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"walletTypes.d.ts","sourceRoot":"","sources":["walletTypes.ts"],"names":[],"mappings":"AAgBA;;;;;;;;GAQG;AAEH;;GAEG;AACH,OAAO,EAAE,UAAU,EAAsB,MAAM,iBAAiB,CAAC;AACjE,OAAO,KAAK,cAAc,MAAM,wBAAwB,CAAC;AACzD,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,yBAAyB,EAC1B,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAIL,KAAK,EACN,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE5C;;GAEG;AACH,qBAAa,qBAAqB;IAChC;;;OAGG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;;;GAIG;AACH,MAAM,WAAW,uBAAuB;IACtC;;OAEG;IACH,YAAY,EAAE,cAAc,CAAC;IAE7B;;OAEG;IACH,oBAAoB,EAAE,MAAM,EAAE,CAAC;IAE/B;;OAEG;IACH,cAAc,EAAE,yBAAyB,CAAC;IAE1C;;OAEG;IACH,WAAW,EAAE,UAAU,CAAC;IAExB;;OAEG;IACH,QAAQ,EAAE,UAAU,CAAC;IAErB;;OAEG;IACH,QAAQ,EAAE,gBAAgB,CAAC;IAE3B;;;OAGG;IACH,SAAS,EAAE,OAAO,CAAC;IAEnB;;OAEG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/walletTypes.ts b/packages/taler-wallet-core/src/types/walletTypes.ts
new file mode 100644
index 000000000..04f50f29a
--- /dev/null
+++ b/packages/taler-wallet-core/src/types/walletTypes.ts
@@ -0,0 +1,516 @@
+/*
+ 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 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/packages/taler-wallet-core/src/util/RequestThrottler.d.ts.map b/packages/taler-wallet-core/src/util/RequestThrottler.d.ts.map
new file mode 100644
index 000000000..3a2fa1081
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/RequestThrottler.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"RequestThrottler.d.ts","sourceRoot":"","sources":["RequestThrottler.ts"],"names":[],"mappings":"AAiGA;;;;GAIG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,aAAa,CAAyC;IAE9D;;;;OAIG;IACH,OAAO,CAAC,QAAQ;IAShB;;;;OAIG;IACH,aAAa,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO;CAI3C"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/util/RequestThrottler.ts b/packages/taler-wallet-core/src/util/RequestThrottler.ts
new file mode 100644
index 000000000..6f51a72bc
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/RequestThrottler.ts
@@ -0,0 +1,129 @@
+/*
+ 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";
+import { URL } from "./url";
+
+/**
+ * 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/packages/taler-wallet-core/src/util/amounts-test.ts b/packages/taler-wallet-core/src/util/amounts-test.ts
new file mode 100644
index 000000000..afd8caa51
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/amounts-test.ts
@@ -0,0 +1,140 @@
+/*
+ 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/packages/taler-wallet-core/src/util/amounts.d.ts.map b/packages/taler-wallet-core/src/util/amounts.d.ts.map
new file mode 100644
index 000000000..c70d06fb7
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/amounts.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"amounts.d.ts","sourceRoot":"","sources":["amounts.ts"],"names":[],"mappings":"AAgBA;;GAEG;AAEH;;GAEG;AACH,OAAO,EAIL,KAAK,EACN,MAAM,SAAS,CAAC;AAEjB;;GAEG;AACH,eAAO,MAAM,cAAc,YAAM,CAAC;AAElC;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,IAAI,CAAC;AAElC;;GAEG;AACH,eAAO,MAAM,cAAc,QAAU,CAAC;AAEtC;;;GAGG;AACH,MAAM,WAAW,UAAU;IACzB;;OAEG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAEvB;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAE1B;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AAED,eAAO,MAAM,kBAAkB,QAAO,KAAK,CAAC,UAAU,CAK9B,CAAC;AAEzB;;GAEG;AACH,MAAM,WAAW,MAAM;IACrB;;OAEG;IACH,MAAM,EAAE,UAAU,CAAC;IACnB;;OAEG;IACH,SAAS,EAAE,OAAO,CAAC;CACpB;AAED;;GAEG;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AS,IAAI,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CA8B9C;AAGD,eAAO,MAAM,OAAO;;;;;;;;;;;;;;;;CAgBnB,CAAC"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/util/amounts.ts b/packages/taler-wallet-core/src/util/amounts.ts
new file mode 100644
index 000000000..00f4b17d7
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/amounts.ts
@@ -0,0 +1,384 @@
+/*
+ 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,
+ fractionalBase: fractionalBase,
+};
diff --git a/packages/taler-wallet-core/src/util/assertUnreachable.d.ts.map b/packages/taler-wallet-core/src/util/assertUnreachable.d.ts.map
new file mode 100644
index 000000000..64a1ed8e8
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/assertUnreachable.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"assertUnreachable.d.ts","sourceRoot":"","sources":["assertUnreachable.ts"],"names":[],"mappings":"AAgBA,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,KAAK,GAAG,KAAK,CAEjD"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/util/assertUnreachable.ts b/packages/taler-wallet-core/src/util/assertUnreachable.ts
new file mode 100644
index 000000000..ffdf88f04
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/assertUnreachable.ts
@@ -0,0 +1,19 @@
+/*
+ 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/packages/taler-wallet-core/src/util/asyncMemo.d.ts.map b/packages/taler-wallet-core/src/util/asyncMemo.d.ts.map
new file mode 100644
index 000000000..0b764b61b
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/asyncMemo.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"asyncMemo.d.ts","sourceRoot":"","sources":["asyncMemo.ts"],"names":[],"mappings":"AAsBA,qBAAa,cAAc,CAAC,CAAC;IAC3B,OAAO,CAAC,CAAC,CAAK;IACd,OAAO,CAAC,OAAO,CAAqC;IAEpD,OAAO,CAAC,OAAO;IAOf,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAiBnD,KAAK,IAAI,IAAI;CAGd;AAED,qBAAa,iBAAiB,CAAC,CAAC;IAC9B,OAAO,CAAC,CAAC,CAAK;IACd,OAAO,CAAC,SAAS,CAA2B;IAE5C,OAAO,CAAC,OAAO;IAMf,IAAI,CAAC,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAkBtC,KAAK,IAAI,IAAI;CAGd"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/util/asyncMemo.ts b/packages/taler-wallet-core/src/util/asyncMemo.ts
new file mode 100644
index 000000000..6e88081b6
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/asyncMemo.ts
@@ -0,0 +1,87 @@
+/*
+ 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/packages/taler-wallet-core/src/util/codec-test.ts b/packages/taler-wallet-core/src/util/codec-test.ts
new file mode 100644
index 000000000..b429c318c
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/codec-test.ts
@@ -0,0 +1,78 @@
+/*
+ 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/packages/taler-wallet-core/src/util/codec.d.ts.map b/packages/taler-wallet-core/src/util/codec.d.ts.map
new file mode 100644
index 000000000..4304f5cef
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/codec.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"codec.d.ts","sourceRoot":"","sources":["codec.ts"],"names":[],"mappings":"AAgBA;;GAEG;AAIH;;GAEG;AACH,qBAAa,aAAc,SAAQ,KAAK;gBAC1B,OAAO,EAAE,MAAM;CAK5B;AAED;;GAEG;AACH,MAAM,WAAW,OAAO;IACtB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;CAC1B;AAED,wBAAgB,aAAa,CAAC,CAAC,CAAC,EAAE,OAAO,GAAG,MAAM,CAOjD;AASD;;GAEG;AACH,MAAM,WAAW,KAAK,CAAC,CAAC;IACtB;;OAEG;IACH,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,OAAO,KAAK,CAAC,CAAC;CAC7C;AAED,aAAK,eAAe,CAAC,CAAC,SAAS,MAAM,GAAG,EAAE,CAAC,IAAI;KAAG,CAAC,IAAI,CAAC,GAAG,CAAC;CAAE,CAAC;AAY/D,cAAM,kBAAkB,CAAC,UAAU,EAAE,iBAAiB;IACpD,OAAO,CAAC,QAAQ,CAAc;IAE9B;;OAEG;IACH,QAAQ,CAAC,CAAC,SAAS,MAAM,UAAU,GAAG,MAAM,EAAE,CAAC,SAAS,UAAU,CAAC,CAAC,CAAC,EACnE,CAAC,EAAE,CAAC,EACJ,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,GACd,kBAAkB,CAAC,UAAU,EAAE,iBAAiB,GAAG,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IAQ5E;;;;;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A;CAAE,CAAC,CAgB3B;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,EAAE,CAAC,CAgBpE;AAED;;GAEG;AACH,eAAO,MAAM,cAAc,EAAE,KAAK,CAAC,MAAM,CASxC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,eAAe,EAAE,KAAK,CAAC,OAAO,CAS1C,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,cAAc,EAAE,KAAK,CAAC,MAAM,CASxC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,WAAW,EAAE,KAAK,CAAC,GAAG,CAIlC,CAAC;AAEF;;GAEG;AACH,wBAAgB,uBAAuB,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAaxE;AAED;;GAEG;AACH,wBAAgB,qBAAqB,IAAI,KAAK,CAAC,IAAI,CAAC,CAanD;AAED;;GAEG;AACH,wBAAgB,sBAAsB,IAAI,KAAK,CAAC,KAAK,CAAC,CAarD;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAaxE;AAED,wBAAgB,iBAAiB,CAAC,CAAC,EACjC,UAAU,EAAE,KAAK,CAAC,CAAC,CAAC,GACnB,KAAK,CAAC,CAAC,GAAG,SAAS,CAAC,CAStB"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/util/codec.ts b/packages/taler-wallet-core/src/util/codec.ts
new file mode 100644
index 000000000..2ce3c2cba
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/codec.ts
@@ -0,0 +1,406 @@
+/*
+ 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/packages/taler-wallet-core/src/util/helpers-test.ts b/packages/taler-wallet-core/src/util/helpers-test.ts
new file mode 100644
index 000000000..dbecf14b8
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/helpers-test.ts
@@ -0,0 +1,46 @@
+/*
+ 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/packages/taler-wallet-core/src/util/helpers.d.ts.map b/packages/taler-wallet-core/src/util/helpers.d.ts.map
new file mode 100644
index 000000000..789c5c81c
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/helpers.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["helpers.ts"],"names":[],"mappings":"AAgBA;;GAEG;AAEH;;GAEG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAIvC;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,CAGzD;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAWvD;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,CAwB9C;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,GAAG,OAAO,CAclD;AAED,wBAAgB,QAAQ,CAAC,CAAC,EAAE,GAAG,GAAG,GAAG,CAGpC;AAED;;;GAGG;AACH,wBAAgB,OAAO,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,EAAE,CAE5D;AAED;;GAEG;AACH,wBAAgB,IAAI,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,CAarC;AAED;;GAEG;AACH,wBAAgB,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,CAQrD"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/util/helpers.ts b/packages/taler-wallet-core/src/util/helpers.ts
new file mode 100644
index 000000000..ae4b0359e
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/helpers.ts
@@ -0,0 +1,148 @@
+/*
+ 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";
+import { URL } from "./url";
+
+/**
+ * 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/packages/taler-wallet-core/src/util/http.d.ts.map b/packages/taler-wallet-core/src/util/http.d.ts.map
new file mode 100644
index 000000000..edbe41970
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/http.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"http.d.ts","sourceRoot":"","sources":["http.ts"],"names":[],"mappings":"AAgBA;;;GAGG;AAEH;;GAEG;AACH,OAAO,E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AAkC,CAAC,CAAC,EACxD,YAAY,EAAE,YAAY,EAC1B,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,GACd,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAuC7B;AAED,wBAAgB,2BAA2B,CACzC,YAAY,EAAE,YAAY,EAC1B,kBAAkB,EAAE,kBAAkB,GACrC,KAAK,CAYP;AAED,wBAAsB,8BAA8B,CAAC,CAAC,EACpD,YAAY,EAAE,YAAY,EAC1B,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,GACd,OAAO,CAAC,CAAC,CAAC,CAMZ;AAGD,wBAAsB,kCAAkC,CAAC,CAAC,EACxD,YAAY,EAAE,YAAY,GACzB,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC,CAyBlC;AAED,wBAAsB,2BAA2B,CAC/C,YAAY,EAAE,YAAY,GACzB,OAAO,CAAC,IAAI,CAAC,CAiBf;AAED,wBAAsB,8BAA8B,CAAC,CAAC,EACpD,YAAY,EAAE,YAAY,GACzB,OAAO,CAAC,MAAM,CAAC,CAMjB"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/util/http.ts b/packages/taler-wallet-core/src/util/http.ts
new file mode 100644
index 000000000..ad9f0293c
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/http.ts
@@ -0,0 +1,237 @@
+/*
+ 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>;
+}
+
+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/packages/taler-wallet-core/src/util/libtoolVersion-test.ts b/packages/taler-wallet-core/src/util/libtoolVersion-test.ts
new file mode 100644
index 000000000..e58e94759
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/libtoolVersion-test.ts
@@ -0,0 +1,48 @@
+/*
+ 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/packages/taler-wallet-core/src/util/libtoolVersion.d.ts.map b/packages/taler-wallet-core/src/util/libtoolVersion.d.ts.map
new file mode 100644
index 000000000..d0e111aa1
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/libtoolVersion.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"libtoolVersion.d.ts","sourceRoot":"","sources":["libtoolVersion.ts"],"names":[],"mappings":"AAgBA;;;GAGG;AAEH;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC;;OAEG;IACH,UAAU,EAAE,OAAO,CAAC;IACpB;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAC;CACpB;AAQD;;GAEG;AACH,wBAAgB,OAAO,CACrB,EAAE,EAAE,MAAM,EACV,KAAK,EAAE,MAAM,GACZ,kBAAkB,GAAG,SAAS,CAehC"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/util/libtoolVersion.ts b/packages/taler-wallet-core/src/util/libtoolVersion.ts
new file mode 100644
index 000000000..5e9d0b74e
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/libtoolVersion.ts
@@ -0,0 +1,88 @@
+/*
+ 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/packages/taler-wallet-core/src/util/logging.d.ts.map b/packages/taler-wallet-core/src/util/logging.d.ts.map
new file mode 100644
index 000000000..3e289d866
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/logging.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"logging.d.ts","sourceRoot":"","sources":["logging.ts"],"names":[],"mappings":"AAuCA;;;GAGG;AACH,qBAAa,MAAM;IACL,OAAO,CAAC,GAAG;gBAAH,GAAG,EAAE,MAAM;IAE/B,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,IAAI;IAW3C,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,IAAI;IAW3C,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,IAAI;IAW5C,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,IAAI;CAU1C"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/util/logging.ts b/packages/taler-wallet-core/src/util/logging.ts
new file mode 100644
index 000000000..e4f3be2ff
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/logging.ts
@@ -0,0 +1,89 @@
+/*
+ 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/>
+ */
+
+/**
+ * Check if we are running under nodejs.
+ */
+
+const isNode =
+ typeof process !== "undefined" && process.release.name === "node";
+
+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/packages/taler-wallet-core/src/util/payto-test.ts b/packages/taler-wallet-core/src/util/payto-test.ts
new file mode 100644
index 000000000..01280b650
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/payto-test.ts
@@ -0,0 +1,31 @@
+/*
+ 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/packages/taler-wallet-core/src/util/payto.d.ts.map b/packages/taler-wallet-core/src/util/payto.d.ts.map
new file mode 100644
index 000000000..a23c5f5d4
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/payto.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"payto.d.ts","sourceRoot":"","sources":["payto.ts"],"names":[],"mappings":"AAkBA,UAAU,QAAQ;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE;QAAE,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAC;CACpC;AAID;;GAEG;AACH,wBAAgB,mBAAmB,CACjC,CAAC,EAAE,MAAM,EACT,MAAM,EAAE;IAAE,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAA;CAAE,GACjC,MAAM,CAOR;AAED,wBAAgB,aAAa,CAAC,CAAC,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS,CA6B7D"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/util/payto.ts b/packages/taler-wallet-core/src/util/payto.ts
new file mode 100644
index 000000000..a1c47eb2f
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/payto.ts
@@ -0,0 +1,71 @@
+/*
+ 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 { URLSearchParams } from "./url";
+
+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/packages/taler-wallet-core/src/util/promiseUtils.d.ts.map b/packages/taler-wallet-core/src/util/promiseUtils.d.ts.map
new file mode 100644
index 000000000..1ca9a4c99
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/promiseUtils.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"promiseUtils.d.ts","sourceRoot":"","sources":["promiseUtils.ts"],"names":[],"mappings":"AAgBA,MAAM,WAAW,aAAa,CAAC,CAAC;IAC9B,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;IACpB,OAAO,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,IAAI,CAAC;IAC1B,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,CAAC;CAC5B;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,CAAC,KAAK,aAAa,CAAC,CAAC,CAAC,CAYjD;AAED,qBAAa,cAAc;IACzB,OAAO,CAAC,YAAY,CAAgB;IACpC,OAAO,CAAC,mBAAmB,CAAsB;;IAOjD,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAIrB,OAAO,IAAI,IAAI;CAMhB"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/util/promiseUtils.ts b/packages/taler-wallet-core/src/util/promiseUtils.ts
new file mode 100644
index 000000000..d409686d9
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/promiseUtils.ts
@@ -0,0 +1,60 @@
+/*
+ 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/packages/taler-wallet-core/src/util/query.d.ts.map b/packages/taler-wallet-core/src/util/query.d.ts.map
new file mode 100644
index 000000000..4b3fc92ea
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/query.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"query.d.ts","sourceRoot":"","sources":["query.ts"],"names":[],"mappings":"AA2BA,OAAO,KAAK,EAAE,wBAAwB,EAAE,UAAU,EAAE,cAAc,EAAa,WAAW,EAAE,WAAW,EAAE,UAAU,EAAgC,MAAM,yBAAyB,CAAC;AAGnL;;GAEG;AACH,eAAO,MAAM,gBAAgB,eAA8B,CAAC;AAE5D;;GAEG;AACH,qBAAa,KAAK,CAAC,CAAC;IAET,IAAI,EAAE,MAAM;IACZ,WAAW,CAAC;IACZ,SAAS,CAAC,OAAM,CAAC,KAAK,CAAC;gBAFvB,IAAI,EAAE,MAAM,EACZ,WAAW,CAAC,sCAA0B,EACtC,SAAS,CAAC,OAAM,CAAC,KAAK,CAAC,aAAA;CAEjC;AAED;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B;;;;;OAKG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AA+DD,aAAK,YAAY,CAAC,CAAC,IAAI,iBAAiB,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAAC;AAEnE,UAAU,iBAAiB,CAAC,CAAC;IAC3B,QAAQ,EAAE,KAAK,CAAC;CACjB;AAED,UAAU,iBAAiB,CAAC,CAAC;IAC3B,QAAQ,EAAE,IAAI,CAAC;IAC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AAC,CAAC,CAAC,GAAG,YAAY,CAAC,CAAC,CAAC;IAMzC,SAAS,CAAC,CAAC,SAAS,WAAW,EAAE,CAAC,EAChC,KAAK,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,EAClB,KAAK,CAAC,EAAE,GAAG,GACV,YAAY,CAAC,CAAC,CAAC;IASZ,sBAAsB,CAAC,CAAC,EAC5B,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,EACpB,CAAC,EAAE,CAAC,CAAC,EAAE,iBAAiB,KAAK,OAAO,CAAC,CAAC,CAAC,GACtC,OAAO,CAAC,CAAC,CAAC;IAIP,uBAAuB,CAAC,CAAC,EAC7B,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,EACpB,CAAC,EAAE,CAAC,CAAC,EAAE,iBAAiB,KAAK,OAAO,CAAC,CAAC,CAAC,GACtC,OAAO,CAAC,CAAC,CAAC;CAGd"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/util/query.ts b/packages/taler-wallet-core/src/util/query.ts
new file mode 100644
index 000000000..53359752e
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/query.ts
@@ -0,0 +1,576 @@
+/*
+ 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";
+import type { idbtypes } from "idb-bridge";
+
+/**
+ * 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?: idbtypes.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: idbtypes.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: idbtypes.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: idbtypes.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: idbtypes.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: idbtypes.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: idbtypes.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: idbtypes.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 idbtypes.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 idbtypes.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: idbtypes.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 idbtypes.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: idbtypes.IDBFactory,
+ databaseName: string,
+ databaseVersion: number,
+ onVersionChange: () => void,
+ onUpgradeNeeded: (
+ db: idbtypes.IDBDatabase,
+ oldVersion: number,
+ newVersion: number,
+ ) => void,
+): Promise<idbtypes.IDBDatabase> {
+ return new Promise<idbtypes.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: idbtypes.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: idbtypes.IDBDatabase) {}
+
+ static deleteDatabase(idbFactory: idbtypes.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: idbtypes.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 idbtypes.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 idbtypes.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/packages/taler-wallet-core/src/util/reserveHistoryUtil-test.ts b/packages/taler-wallet-core/src/util/reserveHistoryUtil-test.ts
new file mode 100644
index 000000000..79022de77
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/reserveHistoryUtil-test.ts
@@ -0,0 +1,285 @@
+/*
+ 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/packages/taler-wallet-core/src/util/reserveHistoryUtil.d.ts.map b/packages/taler-wallet-core/src/util/reserveHistoryUtil.d.ts.map
new file mode 100644
index 000000000..aec8f0715
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/reserveHistoryUtil.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"reserveHistoryUtil.d.ts","sourceRoot":"","sources":["reserveHistoryUtil.ts"],"names":[],"mappings":"AAgBA;;GAEG;AACH,OAAO,EACL,wBAAwB,EAEzB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,kBAAkB,EAEnB,MAAM,6BAA6B,CAAC;AACrC,OAAO,KAAK,OAAO,MAAM,iBAAiB,CAAC;AAK3C;;;;GAIG;AAEH,MAAM,WAAW,2BAA2B;IAC1C;;OAEG;IACH,mBAAmB,EAAE,wBAAwB,EAAE,CAAC;IAEhD;;;OAGG;IACH,aAAa,EAAE,wBAAwB,EAAE,CAAC;IAE1C;;;OAGG;IACH,eAAe,EAAE,wBAAwB,EAAE,CAAC;CAC7C;AAED;;;GAGG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,sBAAsB,EAAE,OAAO,CAAC,UAAU,CAAC;IAE3C;;OAEG;IACH,sBAAsB,EAAE,OAAO,CAAC,UAAU,CAAC;IAE3C;;OAEG;IACH,oBAAoB,EAAE,OAAO,CAAC,UAAU,CAAC;IAEzC;;;OAGG;IACH,eAAe,EAAE,OAAO,CAAC,UAAU,CAAC;CACrC;AA6BD;;GAEG;AACH,wBAAgB,yBAAyB,CACvC,EAAE,EAAE,wBAAwB,EAC5B,EAAE,EAAE,kBAAkB,GACrB,OAAO,CAwBT;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CACrC,YAAY,EAAE,wBAAwB,EAAE,EACxC,QAAQ,EAAE,MAAM,GACf,qBAAqB,CAmFvB;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CACrC,YAAY,EAAE,wBAAwB,EAAE,EACxC,aAAa,EAAE,kBAAkB,EAAE,GAClC,2BAA2B,CAqH7B"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/util/reserveHistoryUtil.ts b/packages/taler-wallet-core/src/util/reserveHistoryUtil.ts
new file mode 100644
index 000000000..855b71a3d
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/reserveHistoryUtil.ts
@@ -0,0 +1,360 @@
+/*
+ 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/packages/taler-wallet-core/src/util/talerconfig.ts b/packages/taler-wallet-core/src/util/talerconfig.ts
new file mode 100644
index 000000000..ec08c352f
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/talerconfig.ts
@@ -0,0 +1,120 @@
+/*
+ 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/packages/taler-wallet-core/src/util/taleruri-test.ts b/packages/taler-wallet-core/src/util/taleruri-test.ts
new file mode 100644
index 000000000..b6c326119
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/taleruri-test.ts
@@ -0,0 +1,184 @@
+/*
+ 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/packages/taler-wallet-core/src/util/taleruri.d.ts.map b/packages/taler-wallet-core/src/util/taleruri.d.ts.map
new file mode 100644
index 000000000..36c16c889
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/taleruri.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"taleruri.d.ts","sourceRoot":"","sources":["taleruri.ts"],"names":[],"mappings":"AAkBA,MAAM,WAAW,YAAY;IAC3B,eAAe,EAAE,MAAM,CAAC;IACxB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;CAChC;AAED,MAAM,WAAW,iBAAiB;IAChC,yBAAyB,EAAE,MAAM,CAAC;IAClC,qBAAqB,EAAE,MAAM,CAAC;CAC/B;AAED,MAAM,WAAW,eAAe;IAC9B,eAAe,EAAE,MAAM,CAAC;IACxB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,YAAY;IAC3B,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,MAAM,CAAC;CACzB;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,MAAM,GAAG,iBAAiB,GAAG,SAAS,CAoBzE;AAED,0BAAkB,YAAY;IAC5B,QAAQ,cAAc;IACtB,aAAa,mBAAmB;IAChC,QAAQ,cAAc;IACtB,WAAW,iBAAiB;IAC5B,kBAAkB,yBAAyB;IAC3C,OAAO,YAAY;CACpB;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,MAAM,GAAG,YAAY,CA2BxD;AA0BD;;;GAGG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS,CAyB/D;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS,CAoB/D;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,CAAC,EAAE,MAAM,GAAG,eAAe,GAAG,SAAS,CAoBrE"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/util/taleruri.ts b/packages/taler-wallet-core/src/util/taleruri.ts
new file mode 100644
index 000000000..43a869afe
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/taleruri.ts
@@ -0,0 +1,215 @@
+/*
+ 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/>
+ */
+
+import { URLSearchParams } from "./url";
+
+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/packages/taler-wallet-core/src/util/testvectors.ts b/packages/taler-wallet-core/src/util/testvectors.ts
new file mode 100644
index 000000000..57ac6e992
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/testvectors.ts
@@ -0,0 +1,36 @@
+/*
+ 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 {
+ setupRefreshPlanchet,
+ encodeCrock,
+ getRandomBytes,
+} from "../crypto/talerCrypto";
+
+export function printTestVectors() {
+ const secretSeed = getRandomBytes(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)}`);
+}
diff --git a/packages/taler-wallet-core/src/util/time.d.ts.map b/packages/taler-wallet-core/src/util/time.d.ts.map
new file mode 100644
index 000000000..c38a23356
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/time.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"time.d.ts","sourceRoot":"","sources":["time.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAA0B,MAAM,SAAS,CAAC;AAkBxD;;GAEG;AAEH,qBAAa,SAAS;IACpB;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;CACjC;AAED,MAAM,WAAW,QAAQ;IACvB;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;CACnC;AAID,wBAAgB,sBAAsB,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAEvD;AAED,wBAAgB,eAAe,IAAI,SAAS,CAI3C;AAED,wBAAgB,oBAAoB,CAClC,QAAQ,EAAE,SAAS,EACnB,GAAG,YAAoB,GACtB,QAAQ,CAWV;AAED,wBAAgB,YAAY,CAAC,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,SAAS,GAAG,SAAS,CAQpE;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,EAAE,EAAE,SAAS,GAAG,SAAS,CAOlE;AAED,wBAAgB,WAAW,CAAC,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,QAAQ,GAAG,QAAQ,CAQhE;AAED,wBAAgB,YAAY,CAAC,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,SAAS,GAAG,MAAM,CAiBjE;AAED,wBAAgB,oBAAoB,CAAC,EAAE,EAAE,SAAS,EAAE,CAAC,EAAE,QAAQ,GAAG,SAAS,CAK1E;AAED,wBAAgB,0BAA0B,CACxC,EAAE,EAAE,SAAS,EACb,CAAC,EAAE,QAAQ,GACV,SAAS,CAQX;AAED,wBAAgB,kBAAkB,CAAC,CAAC,EAAE,SAAS,GAAG,MAAM,CAKvD;AAED,wBAAgB,mBAAmB,CAAC,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,SAAS,GAAG,QAAQ,CAQ1E;AAED,wBAAgB,kBAAkB,CAChC,CAAC,EAAE,SAAS,EACZ,KAAK,EAAE,SAAS,EAChB,GAAG,EAAE,SAAS,GACb,OAAO,CAQT;AAED,eAAO,MAAM,iBAAiB,EAAE,KAAK,CAAC,SAAS,CAc9C,CAAC;AAEF,eAAO,MAAM,gBAAgB,EAAE,KAAK,CAAC,QAAQ,CAc5C,CAAC"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/util/time.ts b/packages/taler-wallet-core/src/util/time.ts
new file mode 100644
index 000000000..5c2f49d12
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/time.ts
@@ -0,0 +1,198 @@
+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/packages/taler-wallet-core/src/util/timer.d.ts.map b/packages/taler-wallet-core/src/util/timer.d.ts.map
new file mode 100644
index 000000000..c2b5e536e
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/timer.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"timer.d.ts","sourceRoot":"","sources":["timer.ts"],"names":[],"mappings":"AAgBA;;;;;GAKG;AAEH;;GAEG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAKlC;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,KAAK,IAAI,IAAI,CAAC;CACf;AAkBD;;GAEG;AACH,eAAO,MAAM,cAAc,EAAE,MAAM,MAa/B,CAAC;AAEL;;GAEG;AACH,wBAAgB,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,WAAW,CAExE;AAED;;GAEG;AACH,wBAAgB,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,WAAW,CAExE;AASD;;GAEG;AACH,qBAAa,UAAU;IACrB,OAAO,CAAC,OAAO,CAAS;IAExB,OAAO,CAAC,QAAQ,CAAwC;IAExD,OAAO,CAAC,KAAK,CAAK;IAElB,0BAA0B,IAAI,IAAI;IAWlC,YAAY,CAAC,OAAO,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAU9C,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,WAAW;IAmBzD,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,WAAW;CAkB1D"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/util/timer.ts b/packages/taler-wallet-core/src/util/timer.ts
new file mode 100644
index 000000000..8eab1399c
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/timer.ts
@@ -0,0 +1,165 @@
+/*
+ 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 = (() => {
+ // @ts-ignore
+ if (typeof process !== "undefined" && process.hrtime) {
+ return () => {
+ const t = process.hrtime();
+ return t[0] * 1e9 + t[1];
+ };
+ }
+
+ // @ts-ignore
+ if (typeof performance !== "undefined") {
+ // @ts-ignore
+ return () => performance.now();
+ }
+
+ 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/packages/taler-wallet-core/src/util/url.d.ts.map b/packages/taler-wallet-core/src/util/url.d.ts.map
new file mode 100644
index 000000000..f238a9b5a
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/url.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"url.d.ts","sourceRoot":"","sources":["url.ts"],"names":[],"mappings":"AAgBA,UAAU,GAAG;IACX,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,IAAI,MAAM,CAAC;IACnB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM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ff --git a/packages/taler-wallet-core/src/util/url.ts b/packages/taler-wallet-core/src/util/url.ts
new file mode 100644
index 000000000..b50b4b466
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/url.ts
@@ -0,0 +1,74 @@
+/*
+ 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/>
+ */
+
+interface URL {
+ hash: string;
+ host: string;
+ hostname: string;
+ href: string;
+ toString(): string;
+ readonly origin: string;
+ password: string;
+ pathname: string;
+ port: string;
+ protocol: string;
+ search: string;
+ readonly searchParams: URLSearchParams;
+ username: string;
+ toJSON(): string;
+}
+
+interface URLSearchParams {
+ append(name: string, value: string): void;
+ delete(name: string): void;
+ get(name: string): string | null;
+ getAll(name: string): string[];
+ has(name: string): boolean;
+ set(name: string, value: string): void;
+ sort(): void;
+ toString(): string;
+ forEach(
+ callbackfn: (value: string, key: string, parent: URLSearchParams) => void,
+ thisArg?: any,
+ ): void;
+}
+
+export interface URLSearchParamsCtor {
+ new (
+ init?: string[][] | Record<string, string> | string | URLSearchParams,
+ ): URLSearchParams;
+}
+
+export interface URLCtor {
+ new (url: string, base?: string | URL): URL;
+}
+
+// @ts-ignore
+const _URL = globalThis.URL;
+if (!_URL) {
+ throw Error("FATAL: URL not available");
+}
+
+export const URL: URLCtor = _URL;
+
+// @ts-ignore
+const _URLSearchParams = globalThis.URLSearchParams;
+
+if (!_URLSearchParams) {
+ throw Error("FATAL: URLSearchParams not available");
+}
+
+export const URLSearchParams: URLSearchParamsCtor = _URLSearchParams;
diff --git a/packages/taler-wallet-core/src/util/wire.ts b/packages/taler-wallet-core/src/util/wire.ts
new file mode 100644
index 000000000..95e324f3c
--- /dev/null
+++ b/packages/taler-wallet-core/src/util/wire.ts
@@ -0,0 +1,51 @@
+/*
+ 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 "../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/packages/taler-wallet-core/src/wallet-test.ts b/packages/taler-wallet-core/src/wallet-test.ts
new file mode 100644
index 000000000..4b06accf2
--- /dev/null
+++ b/packages/taler-wallet-core/src/wallet-test.ts
@@ -0,0 +1,121 @@
+/*
+ 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/packages/taler-wallet-core/src/wallet.d.ts.map b/packages/taler-wallet-core/src/wallet.d.ts.map
new file mode 100644
index 000000000..4c6b1964c
--- /dev/null
+++ b/packages/taler-wallet-core/src/wallet.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"wallet.d.ts","sourceRoot":"","sources":["wallet.ts"],"names":[],"mappings":"AAgBA;;;GAGG;AAEH;;GAEG;AACH,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAE,MA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ts b/packages/taler-wallet-core/src/wallet.ts
new file mode 100644
index 000000000..4a409f58d
--- /dev/null
+++ b/packages/taler-wallet-core/src/wallet.ts
@@ -0,0 +1,882 @@
+/*
+ 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/packages/taler-wallet-core/src/walletCoreApiHandler.d.ts.map b/packages/taler-wallet-core/src/walletCoreApiHandler.d.ts.map
new file mode 100644
index 000000000..e7ab1011a
--- /dev/null
+++ b/packages/taler-wallet-core/src/walletCoreApiHandler.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"walletCoreApiHandler.d.ts","sourceRoot":"","sources":["walletCoreApiHandler.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAelC,OAAO,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AA+N5D,oBAAY,eAAe,GACxB,sBAAsB,GACtB,oBAAoB,CAAC;AAExB,oBAAY,eAAe,GACxB,eAAe,GACf,mBAAmB,CAAC;AAEvB,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,cAAc,CAAC;IACrB,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,sBAAsB;IAErC,IAAI,EAAE,UAAU,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,oBAAoB;IAEnC,IAAI,EAAE,OAAO,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,qBAAqB,CAAC;CAC9B;AAED;;GAEG;AACH,wBAAsB,oBAAoB,CACxC,CAAC,EAAE,MAAM,EACT,SAAS,EAAE,MAAM,EACjB,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,OAAO,GACf,OAAO,CAAC,eAAe,CAAC,CAiC1B"} \ No newline at end of file
diff --git a/packages/taler-wallet-core/src/walletCoreApiHandler.ts b/packages/taler-wallet-core/src/walletCoreApiHandler.ts
new file mode 100644
index 000000000..a0b205485
--- /dev/null
+++ b/packages/taler-wallet-core/src/walletCoreApiHandler.ts
@@ -0,0 +1,318 @@
+/*
+ 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}`,
+ {},
+ ),
+ };
+ }
+ }
+}