wallet-core/packages/taler-wallet-core/src/db.ts

2681 lines
60 KiB
TypeScript
Raw Normal View History

2021-06-10 10:37:49 +02:00
/*
This file is part of GNU Taler
(C) 2021-2022 Taler Systems S.A.
2021-06-10 10:37:49 +02:00
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.
*/
2023-01-11 14:19:24 +01:00
import {
Event,
IDBDatabase,
IDBFactory,
IDBObjectStore,
2023-01-11 14:19:24 +01:00
IDBTransaction,
} from "@gnu-taler/idb-bridge";
import {
AgeCommitmentProof,
2021-05-12 14:16:01 +02:00
AmountJson,
AmountString,
CoinEnvelope,
CoinRefreshRequest,
CoinStatus,
2022-11-01 11:34:20 +01:00
MerchantContractTerms,
DenominationInfo,
2021-11-17 10:23:22 +01:00
DenominationPubKey,
DenomSelectionState,
EddsaPublicKeyString,
EddsaSignatureString,
ExchangeAuditor,
ExchangeGlobalFees,
2021-05-12 14:16:01 +02:00
InternationalizedString,
Location,
2021-05-12 14:16:01 +02:00
MerchantInfo,
PayCoinSelection,
PeerContractTerms,
2021-05-12 14:16:01 +02:00
Product,
RefreshReason,
TalerErrorDetail,
2022-03-18 15:32:41 +01:00
TalerProtocolDuration,
TalerProtocolTimestamp,
TransactionIdStr,
UnblindedSignature,
WireInfo,
2022-11-02 17:02:42 +01:00
HashCodeString,
2022-11-02 17:42:14 +01:00
Amounts,
2022-11-25 03:16:01 +01:00
AttentionPriority,
AttentionInfo,
AbsoluteTime,
2023-01-11 14:19:24 +01:00
Logger,
CoinPublicKeyString,
2021-05-12 14:16:01 +02:00
} from "@gnu-taler/taler-util";
import {
2023-01-11 14:19:24 +01:00
DbAccess,
describeContents,
describeIndex,
describeStore,
2023-01-11 14:19:24 +01:00
GetReadWriteAccess,
IndexDescriptor,
openDatabase,
StoreDescriptor,
StoreWithIndexes,
} from "./util/query.js";
2022-09-16 17:21:54 +02:00
import { RetryInfo, RetryTags } from "./util/retries.js";
2023-01-11 14:19:24 +01:00
import { Wallet } from "./wallet.js";
2019-07-31 01:33:56 +02:00
/**
* This file contains the database schema of the Taler wallet together
* with some helper functions.
*
* Some design considerations:
* - By convention, each object store must have a corresponding "<Name>Record"
* interface defined for it.
* - For records that represent operations, there should be exactly
* one top-level enum field that indicates the status of the operation.
* This field should be present even if redundant, because the field
* will have an index.
* - Amounts are stored as strings, except when they are needed for
* indexing.
* - Every record that has a corresponding transaction item must have
* an index for a mandatory timestamp field.
* - Optional fields should be avoided, use "T | undefined" instead.
2022-09-21 21:13:31 +02:00
* - Do all records have some obvious, indexed field that can
* be used for range queries?
*
* @author Florian Dold <dold@taler.net>
*/
2020-05-08 14:15:23 +02:00
/**
2020-09-08 17:46:11 +02:00
* Name of the Taler database. This is effectively the major
* version of the DB schema. Whenever it changes, custom import logic
* for all previous versions must be written, which should be
* avoided.
2020-05-08 14:15:23 +02:00
*/
2022-11-02 19:07:46 +01:00
export const TALER_DB_NAME = "taler-wallet-main-v9";
/**
* Name of the metadata database. This database is used
* to track major migrations of the main Taler database.
*
* (Minor migrations are handled via upgrade transactions.)
*/
export const TALER_META_DB_NAME = "taler-wallet-meta";
export const CURRENT_DB_CONFIG_KEY = "currentMainDbName";
2019-07-31 01:33:56 +02:00
2019-12-13 13:10:20 +01:00
/**
2020-05-08 14:15:23 +02:00
* 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.
2019-12-13 13:10:20 +01:00
*/
2023-01-11 14:19:24 +01:00
export const WALLET_DB_MINOR_VERSION = 2;
2020-11-16 14:12:37 +01:00
2022-10-14 21:00:13 +02:00
/**
* Ranges for operation status fields.
*
* All individual enums should make sure that the values they
* defined are in the right range.
*/
export enum OperationStatusRange {
2022-10-14 21:00:13 +02:00
// Operations that need to be actively processed.
ACTIVE_START = 10,
ACTIVE_END = 29,
2022-10-14 21:00:13 +02:00
// Operations that need user input, but nothing can be done
// automatically.
USER_ATTENTION_START = 30,
USER_ATTENTION_END = 49,
2022-10-14 21:00:13 +02:00
// Operations that don't need any attention or processing.
DORMANT_START = 50,
DORMANT_END = 69,
}
/**
* Status of a withdrawal.
*/
export enum WithdrawalGroupStatus {
2021-03-17 17:56:37 +01:00
/**
* Reserve must be registered with the bank.
*/
RegisteringBank = 10,
2021-03-17 17:56:37 +01:00
/**
* 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).
*/
WaitConfirmBank = 11,
2021-03-17 17:56:37 +01:00
/**
* Querying reserve status with the exchange.
*/
QueryingStatus = 12,
2021-03-17 17:56:37 +01:00
/**
* Ready for withdrawal.
*/
Ready = 13,
2021-03-17 17:56:37 +01:00
/**
* The corresponding withdraw record has been created.
* No further processing is done, unless explicitly requested
* by the user.
*/
Finished = 50,
2021-03-17 17:56:37 +01:00
/**
* The bank aborted the withdrawal.
*/
BankAborted = 51,
2021-03-17 17:56:37 +01:00
}
/**
2022-10-14 21:00:13 +02:00
* Extra info about a withdrawal that is used
* with a bank-integrated withdrawal.
*/
2021-03-17 17:56:37 +01:00
export interface ReserveBankInfo {
talerWithdrawUri: string;
2021-03-17 17:56:37 +01:00
/**
* URL that the user can be redirected to, and allows
* them to confirm (or abort) the bank-integrated withdrawal.
*/
2022-09-21 21:13:31 +02:00
confirmUrl: string | undefined;
2021-03-17 17:56:37 +01:00
/**
* Exchange payto URI that the bank will use to fund the reserve.
*/
exchangePaytoUri: string;
/**
* Time when the information about this reserve was posted to the bank.
*
* Only applies if bankWithdrawStatusUrl is defined.
*
2022-01-12 16:54:38 +01:00
* Set to undefined if that hasn't happened yet.
2021-03-17 17:56:37 +01:00
*/
2022-09-21 21:13:31 +02:00
timestampReserveInfoPosted: TalerProtocolTimestamp | undefined;
2021-03-17 17:56:37 +01:00
/**
* Time when the reserve was confirmed by the bank.
*
* Set to undefined if not confirmed yet.
*/
2022-09-21 21:13:31 +02:00
timestampBankConfirmed: TalerProtocolTimestamp | undefined;
2021-03-17 17:56:37 +01:00
}
/**
* Record that indicates the wallet trusts
* a particular auditor.
2021-03-17 17:56:37 +01:00
*/
export interface AuditorTrustRecord {
/**
* Currency that we trust this auditor for.
*/
currency: string;
2021-03-17 17:56:37 +01:00
/**
2021-05-12 16:18:32 +02:00
* Base URL of the auditor.
2021-03-17 17:56:37 +01:00
*/
2021-05-12 16:18:32 +02:00
auditorBaseUrl: string;
/**
* Public key of the auditor.
*/
auditorPub: string;
2021-03-17 17:56:37 +01:00
/**
2021-05-12 16:18:32 +02:00
* UIDs for the operation of adding this auditor
* as a trusted auditor.
2022-09-21 21:13:31 +02:00
*
* (Used for backup/sync merging and tombstones.)
2021-05-12 16:18:32 +02:00
*/
uids: string[];
}
/**
* Record to indicate trust for a particular exchange.
*/
export interface ExchangeTrustRecord {
/**
* Currency that we trust this exchange for.
*/
currency: string;
2021-05-12 16:18:32 +02:00
/**
* Canonicalized exchange base URL.
2021-03-17 17:56:37 +01:00
*/
exchangeBaseUrl: string;
2021-05-12 16:18:32 +02:00
/**
* Master public key of the exchange.
*/
exchangeMasterPub: string;
/**
* UIDs for the operation of adding this exchange
* as trusted.
*/
uids: string[];
2021-03-17 17:56:37 +01:00
}
/**
* Status of a denomination.
*/
2021-08-24 15:43:06 +02:00
export enum DenominationVerificationStatus {
2021-03-17 17:56:37 +01:00
/**
* Verification was delayed.
*/
2022-09-21 21:13:31 +02:00
Unverified = OperationStatusRange.ACTIVE_START,
2021-03-17 17:56:37 +01:00
/**
* Verified as valid.
*/
2022-09-21 21:13:31 +02:00
VerifiedGood = OperationStatusRange.DORMANT_START,
2021-03-17 17:56:37 +01:00
/**
* Verified as invalid.
*/
2022-09-21 21:13:31 +02:00
VerifiedBad = OperationStatusRange.DORMANT_START + 1,
2021-03-17 17:56:37 +01:00
}
export interface DenomFees {
2021-03-17 17:56:37 +01:00
/**
* Fee for withdrawing.
*/
2022-11-02 17:42:14 +01:00
feeWithdraw: AmountString;
2021-03-17 17:56:37 +01:00
/**
* Fee for depositing.
*/
2022-11-02 17:42:14 +01:00
feeDeposit: AmountString;
2021-03-17 17:56:37 +01:00
/**
* Fee for refreshing.
*/
2022-11-02 17:42:14 +01:00
feeRefresh: AmountString;
2021-03-17 17:56:37 +01:00
/**
* Fee for refunding.
*/
2022-11-02 17:42:14 +01:00
feeRefund: AmountString;
}
/**
* Denomination record as stored in the wallet's database.
*/
export interface DenominationRecord {
currency: string;
amountVal: number;
amountFrac: number;
/**
* The denomination public key.
*/
denomPub: DenominationPubKey;
/**
* Hash of the denomination public key.
* Stored in the database for faster lookups.
*/
denomPubHash: string;
fees: DenomFees;
2021-03-17 17:56:37 +01:00
/**
* Validity start date of the denomination.
*/
2022-03-18 15:32:41 +01:00
stampStart: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
/**
* Date after which the currency can't be withdrawn anymore.
*/
2022-03-18 15:32:41 +01:00
stampExpireWithdraw: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
/**
* Date after the denomination officially doesn't exist anymore.
*/
2022-03-18 15:32:41 +01:00
stampExpireLegal: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
/**
* Data after which coins of this denomination can't be deposited anymore.
*/
2022-03-18 15:32:41 +01:00
stampExpireDeposit: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
/**
* Signature by the exchange's master key over the denomination
* information.
*/
masterSig: string;
/**
* Did we verify the signature on the denomination?
*/
2021-08-24 15:43:06 +02:00
verificationStatus: DenominationVerificationStatus;
2021-03-17 17:56:37 +01:00
/**
* 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;
/**
* Master public key of the exchange that made the signature
* on the denomination.
*/
exchangeMasterPub: string;
/**
* Latest list issue date of the "/keys" response
* that includes this denomination.
*/
2022-03-18 15:32:41 +01:00
listIssueDate: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
}
export namespace DenominationRecord {
export function getValue(d: DenominationRecord): AmountJson {
return {
currency: d.currency,
fraction: d.amountFrac,
value: d.amountVal,
};
}
export function toDenomInfo(d: DenominationRecord): DenominationInfo {
return {
denomPub: d.denomPub,
denomPubHash: d.denomPubHash,
2022-11-02 17:42:14 +01:00
feeDeposit: Amounts.stringify(d.fees.feeDeposit),
feeRefresh: Amounts.stringify(d.fees.feeRefresh),
feeRefund: Amounts.stringify(d.fees.feeRefund),
feeWithdraw: Amounts.stringify(d.fees.feeWithdraw),
stampExpireDeposit: d.stampExpireDeposit,
stampExpireLegal: d.stampExpireLegal,
stampExpireWithdraw: d.stampExpireWithdraw,
stampStart: d.stampStart,
2022-11-02 17:42:14 +01:00
value: Amounts.stringify(DenominationRecord.getValue(d)),
exchangeBaseUrl: d.exchangeBaseUrl,
};
}
}
export interface ExchangeSignkeysRecord {
stampStart: TalerProtocolTimestamp;
stampExpire: TalerProtocolTimestamp;
stampEnd: TalerProtocolTimestamp;
signkeyPub: EddsaPublicKeyString;
masterSig: EddsaSignatureString;
/**
* Exchange details that thiis signkeys record belongs to.
*/
exchangeDetailsRowId: number;
}
/**
2022-10-14 21:00:13 +02:00
* Exchange details for a particular
* (exchangeBaseUrl, masterPublicKey, currency) tuple.
*/
export interface ExchangeDetailsRecord {
rowId?: number;
2021-03-17 17:56:37 +01:00
/**
* Master public key of the exchange.
*/
masterPublicKey: string;
exchangeBaseUrl: string;
2021-03-17 17:56:37 +01:00
/**
* Currency that the exchange offers.
*/
currency: string;
/**
* Auditors (partially) auditing the exchange.
*/
2021-11-27 20:56:58 +01:00
auditors: ExchangeAuditor[];
2021-03-17 17:56:37 +01:00
/**
* Last observed protocol version.
*/
2022-10-14 21:00:13 +02:00
protocolVersionRange: string;
2021-03-17 17:56:37 +01:00
2022-03-18 15:32:41 +01:00
reserveClosingDelay: TalerProtocolDuration;
2021-03-17 17:56:37 +01:00
2022-10-12 19:36:30 +02:00
/**
* Fees for exchange services
*/
globalFees: ExchangeGlobalFees[];
/**
* Etag of the current ToS of the exchange.
*/
tosCurrentEtag: string;
/**
* Information about ToS acceptance from the user.
*/
tosAccepted:
| {
etag: string;
timestamp: TalerProtocolTimestamp;
}
| undefined;
wireInfo: WireInfo;
2022-11-01 15:31:48 +01:00
/**
* Age restrictions supported by the exchange (bitmask).
*/
ageMask?: number;
}
export interface ExchangeTosRecord {
exchangeBaseUrl: string;
etag: string;
/**
* Terms of service text or undefined if not downloaded yet.
*
* This is just used as a cache of the last downloaded ToS.
*
*/
termsOfServiceText: string | undefined;
/**
* Content-type of the last downloaded termsOfServiceText.
*/
termsOfServiceContentType: string | undefined;
2021-03-17 17:56:37 +01:00
}
export interface ExchangeDetailsPointer {
masterPublicKey: string;
currency: string;
/**
* Timestamp when the (masterPublicKey, currency) pointer
* has been updated.
*/
2022-03-18 15:32:41 +01:00
updateClock: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
}
/**
* Exchange record as stored in the wallet's database.
*/
export interface ExchangeRecord {
/**
* Base url of the exchange.
*/
baseUrl: string;
/**
* Pointer to the current exchange details.
2022-10-14 21:00:13 +02:00
*
* Should usually not change. Only changes when the
* exchange advertises a different master public key and/or
* currency.
*
2022-11-02 17:09:59 +01:00
* We could use a rowID here, but having the currency in the
2022-11-02 17:42:14 +01:00
* details pointer lets us do fewer DB queries
*/
detailsPointer: ExchangeDetailsPointer | undefined;
2021-03-17 17:56:37 +01:00
/**
* Is this a permanent or temporary exchange record?
*/
permanent: boolean;
/**
* Last time when the exchange was updated (both /keys and /wire).
2021-03-17 17:56:37 +01:00
*/
2022-03-18 15:32:41 +01:00
lastUpdate: TalerProtocolTimestamp | undefined;
2021-03-17 17:56:37 +01:00
/**
* Next scheduled update for the exchange.
2021-06-09 15:14:17 +02:00
*
* (This field must always be present, so we can index on the timestamp.)
2021-03-17 17:56:37 +01:00
*/
2022-03-18 15:32:41 +01:00
nextUpdate: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
lastKeysEtag: string | undefined;
lastWireEtag: string | undefined;
/**
* Next time that we should check if coins need to be refreshed.
*
* Updated whenever the exchange's denominations are updated or when
* the refresh check has been done.
*/
2022-03-18 15:32:41 +01:00
nextRefreshCheck: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
/**
* Public key of the reserve that we're currently using for
* receiving P2P payments.
*/
2022-10-14 22:56:29 +02:00
currentMergeReserveRowId?: number;
2021-03-17 17:56:37 +01:00
}
2022-10-14 21:00:13 +02:00
export enum PlanchetStatus {
Pending = 10 /* ACTIVE_START */,
2022-11-01 13:39:42 +01:00
KycRequired = 11 /* ACTIVE_START + 1 */,
2022-10-14 21:00:13 +02:00
WithdrawalDone = 50 /* DORMANT_START */,
}
2021-03-17 17:56:37 +01:00
/**
* 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;
2022-10-14 21:00:13 +02:00
planchetStatus: PlanchetStatus;
2021-03-17 17:56:37 +01:00
lastError: TalerErrorDetail | undefined;
2021-03-17 17:56:37 +01:00
denomPubHash: string;
blindingKey: string;
withdrawSig: string;
coinEv: CoinEnvelope;
2021-03-17 17:56:37 +01:00
coinEvHash: string;
ageCommitmentProof?: AgeCommitmentProof;
2021-03-17 17:56:37 +01:00
}
export enum CoinSourceType {
Withdraw = "withdraw",
Refresh = "refresh",
Tip = "tip",
}
export interface WithdrawCoinSource {
type: CoinSourceType.Withdraw;
/**
* Can be the empty string for orphaned coins.
*/
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;
refreshGroupId: string;
2021-03-17 17:56:37 +01:00
oldCoinPub: string;
}
export interface TipCoinSource {
type: CoinSourceType.Tip;
walletTipId: string;
coinIndex: number;
}
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;
/**
* Hash of the public key that signs the coin.
*/
denomPubHash: string;
/**
* Unblinded signature by the exchange.
*/
2021-11-17 10:23:22 +01:00
denomSig: UnblindedSignature;
2021-03-17 17:56:37 +01:00
/**
* Base URL that identifies the exchange from which we got the
* coin.
*/
exchangeBaseUrl: string;
/**
* Blinding key used when withdrawing the coin.
* Potentionally used again during payback.
*/
blindingKey: string;
/**
* Hash of the coin envelope.
*
* Stored here for indexing purposes, so that when looking at a
* reserve history, we can quickly find the coin for a withdrawal transaction.
*/
coinEvHash: string;
/**
* Status of the coin.
*/
status: CoinStatus;
/**
* Information about what the coin has been allocated for.
2022-09-21 21:13:31 +02:00
*
* Used for:
* - Diagnostics
* - Idempotency of applying a coin selection (e.g. after re-selection)
*/
spendAllocation: CoinAllocation | undefined;
2022-10-14 21:00:13 +02:00
/**
* Maximum age of purchases that can be made with this coin.
*
2022-10-15 16:25:44 +02:00
* (Used for indexing, redundant with {@link ageCommitmentProof}).
2022-10-14 21:00:13 +02:00
*/
maxAge: number;
2022-09-21 21:13:31 +02:00
ageCommitmentProof: AgeCommitmentProof | undefined;
}
2022-10-14 21:00:13 +02:00
/**
* Coin allocation, i.e. what a coin has been used for.
*/
export interface CoinAllocation {
/**
* ID of the allocation, should be the ID of the transaction that
*/
id: TransactionIdStr;
amount: AmountString;
2021-03-17 17:56:37 +01:00
}
/**
* Status of a tip we got from a merchant.
*/
export interface TipRecord {
/**
* Has the user accepted the tip? Only after the tip has been accepted coins
* withdrawn from the tip may be used.
*/
2022-03-18 15:32:41 +01:00
acceptedTimestamp: TalerProtocolTimestamp | undefined;
2021-03-17 17:56:37 +01:00
/**
* The tipped amount.
*/
2022-11-02 17:42:14 +01:00
tipAmountRaw: AmountString;
2021-03-17 17:56:37 +01:00
/**
* Effect on the balance (including fees etc).
*/
2022-11-02 17:42:14 +01:00
tipAmountEffective: AmountString;
2021-03-17 17:56:37 +01:00
/**
* Timestamp, the tip can't be picked up anymore after this deadline.
*/
2022-03-18 15:32:41 +01:00
tipExpiration: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
/**
* The exchange that will sign our coins, chosen by the merchant.
*/
exchangeBaseUrl: string;
/**
* Base URL of the merchant that is giving us the tip.
*/
merchantBaseUrl: string;
/**
* Denomination selection made by the wallet for picking up
* this tip.
*
* FIXME: Put this into some DenomSelectionCacheRecord instead of
* storing it here!
2021-03-17 17:56:37 +01:00
*/
denomsSel: DenomSelectionState;
denomSelUid: string;
2021-03-17 17:56:37 +01:00
/**
* Tip ID chosen by the wallet.
*/
walletTipId: string;
/**
* Secret seed used to derive planchets for this tip.
*/
secretSeed: string;
/**
* The merchant's identifier for this tip.
*/
merchantTipId: string;
2022-03-18 15:32:41 +01:00
createdTimestamp: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
/**
* Timestamp for when the wallet finished picking up the tip
* from the merchant.
*/
2022-03-18 15:32:41 +01:00
pickedUpTimestamp: TalerProtocolTimestamp | undefined;
2021-03-17 17:56:37 +01:00
}
2021-08-24 14:25:46 +02:00
export enum RefreshCoinStatus {
2022-09-21 21:13:31 +02:00
Pending = OperationStatusRange.ACTIVE_START,
Finished = OperationStatusRange.DORMANT_START,
2021-08-24 14:25:46 +02:00
/**
* The refresh for this coin has been frozen, because of a permanent error.
* More info in lastErrorPerCoin.
*/
2022-09-21 21:13:31 +02:00
Frozen = OperationStatusRange.DORMANT_START + 1,
2021-08-24 14:25:46 +02:00
}
2022-01-11 21:00:12 +01:00
export enum OperationStatus {
2022-09-21 21:13:31 +02:00
Finished = OperationStatusRange.DORMANT_START,
Pending = OperationStatusRange.ACTIVE_START,
2022-01-11 21:00:12 +01:00
}
2022-10-14 21:00:13 +02:00
export enum RefreshOperationStatus {
Pending = 10 /* ACTIVE_START */,
Finished = 50 /* DORMANT_START */,
FinishedWithError = 51 /* DORMANT_START + 1 */,
}
2023-01-15 21:48:41 +01:00
export enum TransactionStatus {
Unknown = 10,
Accepted = 20,
KycRequired = 30,
Wired = 40,
}
/**
* Additional information about the reason of a refresh.
*/
export interface RefreshReasonDetails {
proposalId?: string;
}
/**
* Group of refresh operations. The refreshed coins do not
* have to belong to the same exchange, but must have the same
* currency.
2023-01-09 12:33:41 +01:00
*
* FIXME: Should include the currency as a top-level field,
* but we need to write a migration for that.
*/
2021-03-17 17:56:37 +01:00
export interface RefreshGroupRecord {
2022-10-14 21:00:13 +02:00
operationStatus: RefreshOperationStatus;
2022-01-11 21:00:12 +01:00
2022-09-05 18:12:30 +02:00
// FIXME: Put this into a different object store?
lastErrorPerCoin: { [coinIndex: number]: TalerErrorDetail };
2021-03-17 17:56:37 +01:00
2021-08-24 14:25:46 +02:00
/**
* Unique, randomly generated identifier for this group of
* refresh operations.
*/
2021-03-17 17:56:37 +01:00
refreshGroupId: string;
/**
* Currency of this refresh group.
2023-01-09 12:33:41 +01:00
*
* FIXME: Write a migration to add this to earlier DB versions.
*/
currency: string;
2021-08-24 14:25:46 +02:00
/**
* Reason why this refresh group has been created.
*/
2021-03-17 17:56:37 +01:00
reason: RefreshReason;
/**
* Extra information depending on the reason.
*/
reasonDetails?: RefreshReasonDetails;
2021-03-17 17:56:37 +01:00
oldCoinPubs: string[];
// FIXME: Should this go into a separate
// object store for faster updates?
2021-03-17 17:56:37 +01:00
refreshSessionPerCoin: (RefreshSessionRecord | undefined)[];
2022-11-02 17:42:14 +01:00
inputPerCoin: AmountString[];
2021-03-17 17:56:37 +01:00
2022-11-02 17:42:14 +01:00
estimatedOutputPerCoin: AmountString[];
2021-03-17 17:56:37 +01:00
/**
* 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.
*/
2021-08-24 14:25:46 +02:00
statusPerCoin: RefreshCoinStatus[];
2021-03-17 17:56:37 +01:00
2022-03-18 15:32:41 +01:00
timestampCreated: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
/**
* Timestamp when the refresh session finished.
*/
2022-03-18 15:32:41 +01:00
timestampFinished: TalerProtocolTimestamp | undefined;
2021-03-17 17:56:37 +01:00
}
/**
* Ongoing refresh
*/
export interface RefreshSessionRecord {
/**
* 512-bit secret that can be used to derive
* the other cryptographic material for the refresh session.
*/
sessionSecretSeed: string;
/**
* Sum of the value of denominations we want
* to withdraw in this session, without fees.
*/
2022-11-02 17:42:14 +01:00
amountRefreshOutput: AmountString;
2021-03-17 17:56:37 +01:00
/**
* Hashed denominations of the newly requested coins.
*/
newDenoms: {
denomPubHash: string;
count: number;
}[];
/**
* The no-reveal-index after we've done the melting.
*/
norevealIndex?: number;
}
export 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 {
// Execution time as claimed by the merchant
2022-03-18 15:32:41 +01:00
executionTime: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
/**
* Time when the wallet became aware of the refund.
*/
2022-03-18 15:32:41 +01:00
obtainedTime: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
2022-11-02 17:42:14 +01:00
refundAmount: AmountString;
2021-03-17 17:56:37 +01:00
2022-11-02 17:42:14 +01:00
refundFee: AmountString;
2021-03-17 17:56:37 +01:00
/**
* 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.
*/
2022-11-02 17:42:14 +01:00
totalRefreshCostBound: AmountString;
2021-03-17 17:56:37 +01:00
coinPub: string;
rtransactionId: number;
}
/**
* 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 enum RefundReason {
/**
* Normal refund given by the merchant.
*/
NormalRefund = "normal-refund",
/**
* Refund from an aborted payment.
*/
AbortRefund = "abort-pay-refund",
}
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;
/**
* Fulfillment URL, or the empty string if the order has no fulfillment URL.
*
* Stored as a non-nullable string as we use this field for IndexedDB indexing.
*/
fulfillmentUrl: string;
contractTermsHash: string;
fulfillmentMessage?: string;
fulfillmentMessageI18n?: InternationalizedString;
merchantSig: string;
merchantPub: string;
merchant: MerchantInfo;
2022-11-02 17:42:14 +01:00
amount: AmountString;
2021-03-17 17:56:37 +01:00
orderId: string;
merchantBaseUrl: string;
summary: string;
2022-03-18 15:32:41 +01:00
autoRefund: TalerProtocolDuration | undefined;
2022-11-02 17:42:14 +01:00
maxWireFee: AmountString;
2021-03-17 17:56:37 +01:00
wireFeeAmortization: number;
2022-03-18 15:32:41 +01:00
payDeadline: TalerProtocolTimestamp;
refundDeadline: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
allowedAuditors: AllowedAuditorInfo[];
allowedExchanges: AllowedExchangeInfo[];
2022-03-18 15:32:41 +01:00
timestamp: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
wireMethod: string;
wireInfoHash: string;
2022-11-02 17:42:14 +01:00
maxDepositFee: AmountString;
minimumAge?: number;
deliveryDate: TalerProtocolTimestamp | undefined;
deliveryLocation: Location | undefined;
2021-03-17 17:56:37 +01:00
}
2022-10-08 23:45:49 +02:00
export enum PurchaseStatus {
/**
* Not downloaded yet.
*/
DownloadingProposal = 10,
/**
* The user has accepted the proposal.
*/
Paying = 11,
/**
* Currently in the process of aborting with a refund.
*/
AbortingWithRefund = 12,
/**
* Paying a second time, likely with different session ID
*/
PayingReplay = 13,
/**
* Query for refunds (until query succeeds).
*/
QueryingRefund = 14,
/**
* Query for refund (until auto-refund deadline is reached).
*/
QueryingAutoRefund = 15,
/**
* Proposal downloaded, but the user needs to accept/reject it.
*/
Proposed = 30,
/**
* The user has rejected the proposal.
*/
ProposalRefused = 50,
/**
* Downloading or processing the proposal has failed permanently.
*/
ProposalDownloadFailed = 51,
/**
* Downloaded proposal was detected as a re-purchase.
*/
RepurchaseDetected = 52,
/**
* The payment has been aborted.
*/
PaymentAbortFinished = 53,
/**
* Payment was successful.
*/
Paid = 54,
}
/**
* Partial information about the downloaded proposal.
* Only contains data that is relevant for indexing on the
* "purchases" object stores.
*/
export interface ProposalDownloadInfo {
contractTermsHash: string;
fulfillmentUrl?: string;
currency: string;
contractTermsMerchantSig: string;
}
export interface PurchasePayInfo {
payCoinSelection: PayCoinSelection;
2022-11-02 17:42:14 +01:00
totalPayCost: AmountString;
payCoinSelectionUid: string;
2021-03-17 17:56:37 +01:00
}
/**
* Record that stores status information about one purchase, starting from when
* the customer accepts a proposal. Includes refund status if applicable.
*
2022-10-14 21:00:13 +02:00
* Key: {@link proposalId}
* Operation status: {@link purchaseStatus}
2021-03-17 17:56:37 +01:00
*/
export interface PurchaseRecord {
/**
* Proposal ID for this purchase. Uniquely identifies the
* purchase and the proposal.
* Assigned by the wallet.
2021-03-17 17:56:37 +01:00
*/
proposalId: string;
/**
* Order ID, assigned by the merchant.
*/
orderId: string;
merchantBaseUrl: string;
/**
* Claim token used when downloading the contract terms.
*/
claimToken: string | undefined;
/**
* Session ID we got when downloading the contract.
*/
downloadSessionId: string | undefined;
/**
* If this purchase is a repurchase, this field identifies the original purchase.
*/
repurchaseProposalId: string | undefined;
2022-10-08 23:45:49 +02:00
purchaseStatus: PurchaseStatus;
2021-03-17 17:56:37 +01:00
/**
* Private key for the nonce.
*/
noncePriv: string;
/**
* Public key for the nonce.
*/
noncePub: string;
/**
* Downloaded and parsed proposal data.
*/
download: ProposalDownloadInfo | undefined;
2021-03-17 17:56:37 +01:00
payInfo: PurchasePayInfo | undefined;
2021-03-17 17:56:37 +01:00
/**
* Pending removals from pay coin selection.
2021-05-12 14:16:01 +02:00
*
2021-03-17 17:56:37 +01:00
* Used when a the pay coin selection needs to be changed
* because a coin became known as double-spent or invalid,
* but a new coin selection can't immediately be done, as
* there is not enough balance (e.g. when waiting for a refresh).
*/
pendingRemovedCoinPubs?: string[];
/**
* Timestamp of the first time that sending a payment to the merchant
* for this purchase was successful.
*/
2022-03-18 15:32:41 +01:00
timestampFirstSuccessfulPay: TalerProtocolTimestamp | undefined;
2021-03-17 17:56:37 +01:00
merchantPaySig: string | undefined;
/**
* When was the purchase record created?
*/
timestamp: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
/**
* When was the purchase made?
* Refers to the time that the user accepted.
*/
timestampAccept: TalerProtocolTimestamp | undefined;
2021-03-17 17:56:37 +01:00
/**
* Pending refunds for the purchase. A refund is pending
* when the merchant reports a transient error from the exchange.
*
2022-09-05 18:12:30 +02:00
* FIXME: Put this into a separate object store?
2021-03-17 17:56:37 +01:00
*/
refunds: { [refundKey: string]: WalletRefundItem };
/**
* When was the last refund made?
* Set to 0 if no refund was made on the purchase.
*/
2022-03-18 15:32:41 +01:00
timestampLastRefundStatus: TalerProtocolTimestamp | undefined;
2021-03-17 17:56:37 +01:00
/**
* Last session signature that we submitted to /pay (if any).
*/
lastSessionId: string | undefined;
/**
* Continue querying the refund status until this deadline has expired.
*/
2022-03-18 15:32:41 +01:00
autoRefundDeadline: TalerProtocolTimestamp | undefined;
2021-08-24 15:08:34 +02:00
2022-05-14 23:09:33 +02:00
/**
* How much merchant has refund to be taken but the wallet
* did not picked up yet
*/
2022-11-02 17:42:14 +01:00
refundAmountAwaiting: AmountString | undefined;
2021-03-17 17:56:37 +01:00
}
export enum ConfigRecordKey {
WalletBackupState = "walletBackupState",
CurrencyDefaultsApplied = "currencyDefaultsApplied",
DevMode = "devMode",
}
2021-06-14 11:21:29 +02:00
2021-03-17 17:56:37 +01:00
/**
* Configuration key/value entries to configure
* the wallet.
*/
2021-06-14 11:21:29 +02:00
export type ConfigRecord =
| {
key: ConfigRecordKey.WalletBackupState;
2022-09-05 18:12:30 +02:00
value: WalletBackupConfState;
}
| { key: ConfigRecordKey.CurrencyDefaultsApplied; value: boolean }
| { key: ConfigRecordKey.DevMode; value: boolean };
2021-06-14 11:21:29 +02:00
export interface WalletBackupConfState {
deviceId: string;
walletRootPub: string;
walletRootPriv: string;
/**
* Last hash of the canonicalized plain-text backup.
*/
lastBackupPlainHash?: string;
/**
* Timestamp stored in the last backup.
*/
2022-03-18 15:32:41 +01:00
lastBackupTimestamp?: TalerProtocolTimestamp;
2021-06-14 11:21:29 +02:00
/**
* Last time we tried to do a backup.
*/
2022-03-18 15:32:41 +01:00
lastBackupCheckTimestamp?: TalerProtocolTimestamp;
2021-06-14 11:21:29 +02:00
lastBackupNonce?: string;
2021-03-17 17:56:37 +01:00
}
export const enum WithdrawalRecordType {
BankManual = "bank-manual",
BankIntegrated = "bank-integrated",
PeerPullCredit = "peer-pull-credit",
PeerPushCredit = "peer-push-credit",
Recoup = "recoup",
}
export interface WgInfoBankIntegrated {
withdrawalType: WithdrawalRecordType.BankIntegrated;
/**
* Extra state for when this is a withdrawal involving
* a Taler-integrated bank.
*/
bankInfo: ReserveBankInfo;
}
export interface WgInfoBankManual {
withdrawalType: WithdrawalRecordType.BankManual;
}
export interface WgInfoBankPeerPull {
withdrawalType: WithdrawalRecordType.PeerPullCredit;
contractTerms: any;
/**
* Needed to quickly construct the taler:// URI for the counterparty
* without a join.
*/
contractPriv: string;
}
export interface WgInfoBankPeerPush {
withdrawalType: WithdrawalRecordType.PeerPushCredit;
contractTerms: any;
}
export interface WgInfoBankRecoup {
withdrawalType: WithdrawalRecordType.Recoup;
}
export type WgInfo =
| WgInfoBankIntegrated
| WgInfoBankManual
| WgInfoBankPeerPull
| WgInfoBankPeerPush
| WgInfoBankRecoup;
export type KycUserType = "individual" | "business";
export interface KycPendingInfo {
paytoHash: string;
requirementRow: number;
}
2021-03-17 17:56:37 +01:00
/**
* 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 {
2022-01-12 16:54:38 +01:00
/**
* Unique identifier for the withdrawal group.
*/
2021-03-17 17:56:37 +01:00
withdrawalGroupId: string;
wgInfo: WgInfo;
kycPending?: KycPendingInfo;
2021-03-17 17:56:37 +01:00
/**
* Secret seed used to derive planchets.
2022-08-09 15:00:45 +02:00
* Stored since planchets are created lazily.
2021-03-17 17:56:37 +01:00
*/
secretSeed: string;
2022-01-12 16:54:38 +01:00
/**
* Public key of the reserve that we're withdrawing from.
*/
2021-03-17 17:56:37 +01:00
reservePub: string;
2022-08-09 15:00:45 +02:00
/**
* The reserve private key.
*
* FIXME: Already in the reserves object store, redundant!
2022-08-09 15:00:45 +02:00
*/
reservePriv: string;
2022-01-12 16:54:38 +01:00
/**
* The exchange base URL that we're withdrawing from.
* (Redundantly stored, as the reserve record also has this info.)
*/
2021-03-17 17:56:37 +01:00
exchangeBaseUrl: string;
/**
* When was the withdrawal operation started started?
* Timestamp in milliseconds.
*/
2022-03-18 15:32:41 +01:00
timestampStart: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
/**
* When was the withdrawal operation completed?
*/
2022-03-18 15:32:41 +01:00
timestampFinish?: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
2022-08-09 15:00:45 +02:00
/**
* Current status of the reserve.
*/
status: WithdrawalGroupStatus;
2022-08-09 15:00:45 +02:00
/**
* Wire information (as payto URI) for the bank account that
* transferred funds for this reserve.
*
* FIXME: Doesn't this belong to the bankAccounts object store?
2022-08-09 15:00:45 +02:00
*/
senderWire?: string;
/**
* Restrict withdrawals from this reserve to this age.
*/
restrictAge?: number;
/**
* Amount that was sent by the user to fund the reserve.
*/
2022-11-02 17:42:14 +01:00
instructedAmount: AmountString;
/**
* Amount that was observed when querying the reserve that
* we are withdrawing from.
*
* Useful for diagnostics.
*/
2022-11-02 17:42:14 +01:00
reserveBalanceAmount?: AmountString;
2021-03-17 17:56:37 +01:00
/**
* Amount including fees (i.e. the amount subtracted from the
* reserve to withdraw all coins in this withdrawal session).
*
* (Initial amount confirmed by the user, might differ with denomSel
* on reselection.)
2021-03-17 17:56:37 +01:00
*/
2022-11-02 17:42:14 +01:00
rawWithdrawalAmount: AmountString;
2021-03-17 17:56:37 +01:00
/**
* Amount that will be added to the balance when the withdrawal succeeds.
*
* (Initial amount confirmed by the user, might differ with denomSel
* on reselection.)
*/
2022-11-02 17:42:14 +01:00
effectiveWithdrawalAmount: AmountString;
2022-01-12 16:54:38 +01:00
/**
* Denominations selected for withdrawal.
*/
2021-03-17 17:56:37 +01:00
denomsSel: DenomSelectionState;
2022-01-12 16:54:38 +01:00
/**
* UID of the denomination selection.
*
2022-01-12 16:54:38 +01:00
* Used for merging backups.
*
2022-01-12 16:54:38 +01:00
* FIXME: Should this not also include a timestamp for more logical merging?
*/
denomSelUid: string;
2021-03-17 17:56:37 +01:00
}
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;
exchangeBaseUrl: string;
2022-03-18 15:32:41 +01:00
timestampStarted: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
2022-03-18 15:32:41 +01:00
timestampFinished: TalerProtocolTimestamp | undefined;
2021-03-17 17:56:37 +01:00
/**
* 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[];
/**
* Public keys of coins that should be scheduled for refreshing
* after all individual recoups are done.
*/
scheduleRefreshCoins: CoinRefreshRequest[];
2021-03-17 17:56:37 +01:00
}
export enum BackupProviderStateTag {
Provisional = "provisional",
2021-03-17 17:56:37 +01:00
Ready = "ready",
Retrying = "retrying",
2021-03-17 17:56:37 +01:00
}
export type BackupProviderState =
| {
2022-09-05 18:12:30 +02:00
tag: BackupProviderStateTag.Provisional;
}
| {
2022-09-05 18:12:30 +02:00
tag: BackupProviderStateTag.Ready;
nextBackupTimestamp: TalerProtocolTimestamp;
}
| {
2022-09-05 18:12:30 +02:00
tag: BackupProviderStateTag.Retrying;
};
2021-05-12 14:16:01 +02:00
export interface BackupProviderTerms {
supportedProtocolVersion: string;
annualFee: AmountString;
storageLimitInMegabytes: number;
}
2021-03-17 17:56:37 +01:00
export interface BackupProviderRecord {
2021-05-21 11:47:11 +02:00
/**
* Base URL of the provider.
*
2021-05-21 11:47:11 +02:00
* Primary key for the record.
*/
2021-03-17 17:56:37 +01:00
baseUrl: string;
/**
* Name of the provider
*/
name: string;
2021-03-17 17:56:37 +01:00
/**
* Terms of service of the provider.
* Might be unavailable in the DB in certain situations
* (such as loading a recovery document).
*/
2021-05-12 14:16:01 +02:00
terms?: BackupProviderTerms;
2021-03-17 17:56:37 +01:00
/**
* Hash of the last encrypted backup that we already merged
* or successfully uploaded ourselves.
*/
lastBackupHash?: string;
2021-06-23 13:06:32 +02:00
/**
* Last time that we successfully uploaded a backup (or
* the uploaded backup was already current).
*
* Does NOT correspond to the timestamp of the backup,
* which only changes when the backup content changes.
*/
2022-03-18 15:32:41 +01:00
lastBackupCycleTimestamp?: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
/**
* Proposal that we're currently trying to pay for.
*
* (Also included in paymentProposalIds.)
*
* FIXME: Make this part of a proper BackupProviderState?
2021-03-17 17:56:37 +01:00
*/
currentPaymentProposalId?: string;
2022-11-25 03:16:01 +01:00
shouldRetryFreshProposal: boolean;
2021-03-17 17:56:37 +01:00
/**
* Proposals that were used to pay (or attempt to pay) the provider.
*
* Stored to display a history of payments to the provider, and
* to make sure that the wallet isn't overpaying.
*/
paymentProposalIds: string[];
state: BackupProviderState;
2021-05-12 14:16:01 +02:00
/**
* UIDs for the operation that added the backup provider.
*/
uids: string[];
2021-03-17 17:56:37 +01:00
}
/**
* Group of deposits made by the wallet.
*/
export interface DepositGroupRecord {
depositGroupId: string;
merchantPub: string;
merchantPriv: string;
noncePriv: string;
noncePub: string;
/**
* Wire information used by all deposits in this
* deposit group.
*/
wire: {
payto_uri: string;
salt: string;
};
/**
* Verbatim contract terms.
*/
2022-11-01 11:34:20 +01:00
contractTermsRaw: MerchantContractTerms;
2021-03-17 17:56:37 +01:00
contractTermsHash: string;
payCoinSelection: PayCoinSelection;
payCoinSelectionUid: string;
2022-11-02 17:42:14 +01:00
totalPayCost: AmountString;
2021-03-17 17:56:37 +01:00
2022-11-02 17:42:14 +01:00
effectiveDepositAmount: AmountString;
2021-03-17 17:56:37 +01:00
depositedPerCoin: boolean[];
2022-03-18 15:32:41 +01:00
timestampCreated: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
2022-03-18 15:32:41 +01:00
timestampFinished: TalerProtocolTimestamp | undefined;
2021-03-17 17:56:37 +01:00
2022-01-11 21:00:12 +01:00
operationStatus: OperationStatus;
2023-01-15 21:48:41 +01:00
transactionPerCoin: TransactionStatus[];
2021-03-17 17:56:37 +01:00
}
/**
* Record for a deposits that the wallet observed
* as a result of double spending, but which is not
* present in the wallet's own database otherwise.
*/
export interface GhostDepositGroupRecord {
/**
* When multiple deposits for the same contract terms hash
* have a different timestamp, we choose the earliest one.
*/
2022-03-18 15:32:41 +01:00
timestamp: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
contractTermsHash: string;
deposits: {
coinPub: string;
amount: AmountString;
2022-03-18 15:32:41 +01:00
timestamp: TalerProtocolTimestamp;
2021-03-17 17:56:37 +01:00
depositFee: AmountString;
merchantPub: string;
coinSig: string;
wireHash: string;
}[];
}
2021-05-12 15:26:15 +02:00
export interface TombstoneRecord {
/**
* Tombstone ID, with the syntax "tmb:<type>:<key>".
2021-05-12 15:26:15 +02:00
*/
id: string;
}
2022-11-02 17:02:42 +01:00
export enum PeerPushPaymentInitiationStatus {
/**
* Initiated, but no purse created yet.
*/
Initiated = 10 /* ACTIVE_START */,
PurseCreated = 50 /* DORMANT_START */,
2022-01-11 21:00:12 +01:00
}
export interface PeerPushPaymentCoinSelection {
contributions: AmountString[];
coinPubs: CoinPublicKeyString[];
}
/**
* Record for a push P2P payment that this wallet initiated.
*/
export interface PeerPushPaymentInitiationRecord {
/**
* What exchange are funds coming from?
*/
exchangeBaseUrl: string;
/**
* Instructed amount.
*/
amount: AmountString;
totalCost: AmountString;
coinSel: PeerPushPaymentCoinSelection;
2022-11-02 17:02:42 +01:00
contractTermsHash: HashCodeString;
/**
* Purse public key. Used as the primary key to look
* up this record.
*/
pursePub: string;
/**
* Purse private key.
*/
pursePriv: string;
/**
* Public key of the merge capability of the purse.
*/
mergePub: string;
/**
* Private key of the merge capability of the purse.
*/
mergePriv: string;
contractPriv: string;
contractPub: string;
contractTerms: PeerContractTerms;
purseExpiration: TalerProtocolTimestamp;
2022-11-02 17:02:42 +01:00
timestampCreated: TalerProtocolTimestamp;
/**
2022-11-02 17:02:42 +01:00
* Status of the peer push payment initiation.
*/
2022-11-02 17:02:42 +01:00
status: PeerPushPaymentInitiationStatus;
}
export interface PeerPullPaymentInitiationRecord {
/**
* What exchange are we using for the payment request?
*/
exchangeBaseUrl: string;
/**
* Amount requested.
*/
amount: AmountString;
/**
* Purse public key. Used as the primary key to look
* up this record.
*/
pursePub: string;
/**
* Purse private key.
*/
pursePriv: string;
/**
2022-11-02 17:02:42 +01:00
* Hash of the contract terms. Also
* used to look up the contract terms in the DB.
*/
2022-11-02 17:02:42 +01:00
contractTermsHash: string;
mergePub: string;
mergePriv: string;
contractPub: string;
contractPriv: string;
contractTerms: PeerContractTerms;
mergeTimestamp: TalerProtocolTimestamp;
mergeReserveRowId: number;
2022-11-02 17:02:42 +01:00
/**
* Status of the peer pull payment initiation.
*/
status: OperationStatus;
}
/**
* Record for a push P2P payment that this wallet was offered.
*
2022-08-09 15:00:45 +02:00
* Unique: (exchangeBaseUrl, pursePub)
*/
export interface PeerPushPaymentIncomingRecord {
2022-08-09 15:00:45 +02:00
peerPushPaymentIncomingId: string;
exchangeBaseUrl: string;
pursePub: string;
mergePriv: string;
contractPriv: string;
timestamp: TalerProtocolTimestamp;
2022-11-02 17:02:42 +01:00
/**
* Hash of the contract terms. Also
* used to look up the contract terms in the DB.
*/
contractTermsHash: string;
/**
* Status of the peer push payment incoming initiation.
*/
status: OperationStatus;
}
2022-11-02 17:02:42 +01:00
export enum PeerPullPaymentIncomingStatus {
Proposed = 30 /* USER_ATTENTION_START */,
Accepted = 10 /* ACTIVE_START */,
Paid = 50 /* DORMANT_START */,
}
export interface PeerPullPaymentIncomingRecord {
peerPullPaymentIncomingId: string;
pursePub: string;
exchangeBaseUrl: string;
contractTerms: PeerContractTerms;
timestampCreated: TalerProtocolTimestamp;
contractPriv: string;
2022-11-02 17:02:42 +01:00
/**
* Status of the peer push payment incoming initiation.
*/
status: PeerPullPaymentIncomingStatus;
}
2022-09-21 21:47:00 +02:00
/**
* Store for extra information about a reserve.
*
* Mostly used to store the private key for a reserve and to allow
* other records to reference the reserve key pair via a small row ID.
2022-11-02 15:00:05 +01:00
*
* In the future, we might also store KYC info about a reserve here.
2022-09-21 21:47:00 +02:00
*/
export interface ReserveRecord {
2022-09-21 21:47:00 +02:00
rowId?: number;
reservePub: string;
reservePriv: string;
}
2022-09-05 18:12:30 +02:00
export interface OperationRetryRecord {
/**
* Unique identifier for the operation. Typically of
* the format `${opType}-${opUniqueKey}`
*
2022-09-16 17:21:54 +02:00
* @see {@link RetryTags}
2022-09-05 18:12:30 +02:00
*/
id: string;
lastError?: TalerErrorDetail;
retryInfo: RetryInfo;
}
/**
* Availability of coins of a given denomination (and age restriction!).
*
* We can't store this information with the denomination record, as one denomination
* can be withdrawn with multiple age restrictions.
*/
export interface CoinAvailabilityRecord {
currency: string;
amountVal: number;
amountFrac: number;
denomPubHash: string;
exchangeBaseUrl: string;
/**
* Age restriction on the coin, or 0 for no age restriction (or
* denomination without age restriction support).
*/
maxAge: number;
/**
* Number of fresh coins of this denomination that are available.
*/
freshCoinCount: number;
}
export interface ContractTermsRecord {
/**
* Contract terms hash.
*/
h: string;
/**
* Contract terms JSON.
*/
contractTermsRaw: any;
}
2022-11-25 03:16:01 +01:00
export interface UserAttentionRecord {
info: AttentionInfo;
entityId: string;
/**
* When the notification was created.
*/
createdMs: number;
/**
* When the user mark this notification as read.
*/
read: TalerProtocolTimestamp | undefined;
}
/**
* Schema definition for the IndexedDB
* wallet database.
*/
2021-06-09 15:14:17 +02:00
export const WalletStoresV1 = {
coinAvailability: describeStore(
"coinAvailability",
describeContents<CoinAvailabilityRecord>({
keyPath: ["exchangeBaseUrl", "denomPubHash", "maxAge"],
}),
{
byExchangeAgeAvailability: describeIndex("byExchangeAgeAvailability", [
"exchangeBaseUrl",
"maxAge",
"freshCoinCount",
]),
},
),
2021-06-09 15:14:17 +02:00
coins: describeStore(
"coins",
describeContents<CoinRecord>({
2021-06-09 15:14:17 +02:00
keyPath: "coinPub",
}),
{
byBaseUrl: describeIndex("byBaseUrl", "exchangeBaseUrl"),
byDenomPubHash: describeIndex("byDenomPubHash", "denomPubHash"),
byExchangeDenomPubHashAndAgeAndStatus: describeIndex(
"byExchangeDenomPubHashAndAgeAndStatus",
["exchangeBaseUrl", "denomPubHash", "maxAge", "status"],
),
2021-06-09 15:14:17 +02:00
byCoinEvHash: describeIndex("byCoinEvHash", "coinEvHash"),
},
),
reserves: describeStore(
"reserves",
describeContents<ReserveRecord>({
2022-09-21 21:47:00 +02:00
keyPath: "rowId",
autoIncrement: true,
}),
2022-09-21 21:47:00 +02:00
{
byReservePub: describeIndex("byReservePub", "reservePub", {}),
},
),
exchangeTos: describeStore(
"exchangeTos",
describeContents<ExchangeTosRecord>({
keyPath: ["exchangeBaseUrl", "etag"],
}),
{},
),
2021-06-09 15:14:17 +02:00
config: describeStore(
"config",
describeContents<ConfigRecord>({ keyPath: "key" }),
2021-06-09 15:14:17 +02:00
{},
),
auditorTrust: describeStore(
"auditorTrust",
describeContents<AuditorTrustRecord>({
2021-06-09 15:14:17 +02:00
keyPath: ["currency", "auditorBaseUrl"],
}),
{
byAuditorPub: describeIndex("byAuditorPub", "auditorPub"),
byUid: describeIndex("byUid", "uids", {
multiEntry: true,
}),
},
),
exchangeTrust: describeStore(
"exchangeTrust",
describeContents<ExchangeTrustRecord>({
2021-06-09 15:14:17 +02:00
keyPath: ["currency", "exchangeBaseUrl"],
}),
{
byExchangeMasterPub: describeIndex(
"byExchangeMasterPub",
"exchangeMasterPub",
),
},
),
denominations: describeStore(
"denominations",
describeContents<DenominationRecord>({
2021-06-09 15:14:17 +02:00
keyPath: ["exchangeBaseUrl", "denomPubHash"],
}),
{
byExchangeBaseUrl: describeIndex("byExchangeBaseUrl", "exchangeBaseUrl"),
},
),
exchanges: describeStore(
"exchanges",
describeContents<ExchangeRecord>({
2021-06-09 15:14:17 +02:00
keyPath: "baseUrl",
}),
{},
),
exchangeDetails: describeStore(
"exchangeDetails",
describeContents<ExchangeDetailsRecord>({
keyPath: "rowId",
autoIncrement: true,
2021-06-09 15:14:17 +02:00
}),
{
byPointer: describeIndex(
"byDetailsPointer",
["exchangeBaseUrl", "currency", "masterPublicKey"],
{
unique: true,
},
),
},
),
exchangeSignKeys: describeStore(
"exchangeSignKeys",
describeContents<ExchangeSignkeysRecord>({
keyPath: ["exchangeDetailsRowId", "signkeyPub"],
}),
{
byExchangeDetailsRowId: describeIndex("byExchangeDetailsRowId", [
"exchangeDetailsRowId",
]),
},
2021-06-09 15:14:17 +02:00
),
refreshGroups: describeStore(
"refreshGroups",
describeContents<RefreshGroupRecord>({
2021-03-17 17:56:37 +01:00
keyPath: "refreshGroupId",
2021-06-09 15:14:17 +02:00
}),
2022-01-11 21:00:12 +01:00
{
byStatus: describeIndex("byStatus", "operationStatus"),
},
2021-06-09 15:14:17 +02:00
),
recoupGroups: describeStore(
"recoupGroups",
describeContents<RecoupGroupRecord>({
2021-06-09 15:14:17 +02:00
keyPath: "recoupGroupId",
}),
{},
),
purchases: describeStore(
"purchases",
describeContents<PurchaseRecord>({ keyPath: "proposalId" }),
2021-03-17 17:56:37 +01:00
{
2022-10-08 23:45:49 +02:00
byStatus: describeIndex("byStatus", "purchaseStatus"),
2021-06-09 15:14:17 +02:00
byFulfillmentUrl: describeIndex(
"byFulfillmentUrl",
"download.fulfillmentUrl",
2021-06-09 15:14:17 +02:00
),
byUrlAndOrderId: describeIndex("byUrlAndOrderId", [
"merchantBaseUrl",
"orderId",
]),
2021-03-17 17:56:37 +01:00
},
),
2021-06-09 15:14:17 +02:00
tips: describeStore(
"tips",
describeContents<TipRecord>({ keyPath: "walletTipId" }),
2021-06-09 15:14:17 +02:00
{
byMerchantTipIdAndBaseUrl: describeIndex("byMerchantTipIdAndBaseUrl", [
"merchantTipId",
"merchantBaseUrl",
]),
},
),
withdrawalGroups: describeStore(
"withdrawalGroups",
describeContents<WithdrawalGroupRecord>({
2021-06-09 15:14:17 +02:00
keyPath: "withdrawalGroupId",
}),
{
byStatus: describeIndex("byStatus", "status"),
byTalerWithdrawUri: describeIndex(
"byTalerWithdrawUri",
"wgInfo.bankInfo.talerWithdrawUri",
),
2021-06-09 15:14:17 +02:00
},
),
planchets: describeStore(
"planchets",
describeContents<PlanchetRecord>({ keyPath: "coinPub" }),
2021-06-09 15:14:17 +02:00
{
byGroupAndIndex: describeIndex("byGroupAndIndex", [
"withdrawalGroupId",
"coinIdx",
]),
byGroup: describeIndex("byGroup", "withdrawalGroupId"),
byCoinEvHash: describeIndex("byCoinEv", "coinEvHash"),
},
),
bankWithdrawUris: describeStore(
"bankWithdrawUris",
describeContents<BankWithdrawUriRecord>({
2021-06-09 15:14:17 +02:00
keyPath: "talerWithdrawUri",
}),
{},
),
backupProviders: describeStore(
"backupProviders",
describeContents<BackupProviderRecord>({
2021-06-09 15:14:17 +02:00
keyPath: "baseUrl",
}),
{
byPaymentProposalId: describeIndex(
"byPaymentProposalId",
"paymentProposalIds",
{
multiEntry: true,
},
),
},
2021-06-09 15:14:17 +02:00
),
depositGroups: describeStore(
"depositGroups",
describeContents<DepositGroupRecord>({
2021-06-09 15:14:17 +02:00
keyPath: "depositGroupId",
}),
2022-01-11 21:00:12 +01:00
{
byStatus: describeIndex("byStatus", "operationStatus"),
},
2021-06-09 15:14:17 +02:00
),
tombstones: describeStore(
"tombstones",
describeContents<TombstoneRecord>({ keyPath: "id" }),
2021-06-09 15:14:17 +02:00
{},
),
2022-09-05 18:12:30 +02:00
operationRetries: describeStore(
"operationRetries",
describeContents<OperationRetryRecord>({
2022-09-05 18:12:30 +02:00
keyPath: "id",
}),
{},
),
2021-06-09 15:14:17 +02:00
ghostDepositGroups: describeStore(
"ghostDepositGroups",
describeContents<GhostDepositGroupRecord>({
2021-06-09 15:14:17 +02:00
keyPath: "contractTermsHash",
}),
{},
),
peerPushPaymentIncoming: describeStore(
"peerPushPaymentIncoming",
describeContents<PeerPushPaymentIncomingRecord>({
2022-08-09 15:00:45 +02:00
keyPath: "peerPushPaymentIncomingId",
}),
2022-08-09 15:00:45 +02:00
{
byExchangeAndPurse: describeIndex("byExchangeAndPurse", [
"exchangeBaseUrl",
"pursePub",
]),
byStatus: describeIndex("byStatus", "status"),
2022-08-09 15:00:45 +02:00
},
),
peerPullPaymentIncoming: describeStore(
"peerPullPaymentIncoming",
describeContents<PeerPullPaymentIncomingRecord>({
keyPath: "peerPullPaymentIncomingId",
}),
{
byExchangeAndPurse: describeIndex("byExchangeAndPurse", [
"exchangeBaseUrl",
"pursePub",
]),
byStatus: describeIndex("byStatus", "status"),
},
),
peerPullPaymentInitiations: describeStore(
"peerPullPaymentInitiations",
describeContents<PeerPullPaymentInitiationRecord>({
keyPath: "pursePub",
}),
{
byStatus: describeIndex("byStatus", "status"),
},
),
peerPushPaymentInitiations: describeStore(
"peerPushPaymentInitiations",
describeContents<PeerPushPaymentInitiationRecord>({
keyPath: "pursePub",
}),
{
byStatus: describeIndex("byStatus", "status"),
},
),
2022-09-23 20:17:29 +02:00
bankAccounts: describeStore(
"bankAccounts",
describeContents<BankAccountsRecord>({
keyPath: "uri",
}),
{},
),
contractTerms: describeStore(
"contractTerms",
describeContents<ContractTermsRecord>({
keyPath: "h",
}),
{},
),
2022-11-25 03:16:01 +01:00
userAttention: describeStore(
"userAttention",
describeContents<UserAttentionRecord>({
keyPath: ["entityId", "info.type"],
2023-01-11 14:19:24 +01:00
versionAdded: 2,
}),
{},
),
fixups: describeStore(
"fixups",
describeContents<FixupRecord>({
keyPath: "fixupName",
versionAdded: 2,
2022-11-25 03:16:01 +01:00
}),
{},
),
2021-03-17 17:56:37 +01:00
};
2023-01-11 14:19:24 +01:00
/**
* An applied migration.
*/
export interface FixupRecord {
fixupName: string;
}
2022-09-23 20:17:29 +02:00
/**
* User accounts
*/
export interface BankAccountsRecord {
uri: string;
currency: string;
kycCompleted: boolean;
2022-09-23 20:17:29 +02:00
alias: string;
}
2021-06-14 11:21:29 +02:00
export interface MetaConfigRecord {
key: string;
value: any;
}
2021-06-09 15:14:17 +02:00
export const walletMetadataStore = {
metaConfig: describeStore(
"metaConfig",
describeContents<MetaConfigRecord>({ keyPath: "key" }),
2021-06-09 15:14:17 +02:00
{},
),
2021-03-17 17:56:37 +01:00
};
export function exportDb(db: IDBDatabase): Promise<any> {
const dump = {
name: db.name,
stores: {} as { [s: string]: any },
version: db.version,
};
return new Promise((resolve, reject) => {
const tx = db.transaction(Array.from(db.objectStoreNames));
tx.addEventListener("complete", () => {
resolve(dump);
});
// tslint:disable-next-line:prefer-for-of
for (let i = 0; i < db.objectStoreNames.length; i++) {
const name = db.objectStoreNames[i];
const storeDump = {} as { [s: string]: any };
dump.stores[name] = storeDump;
tx.objectStore(name)
.openCursor()
.addEventListener("success", (e: Event) => {
const cursor = (e.target as any).result;
if (cursor) {
storeDump[cursor.key] = cursor.value;
cursor.continue();
}
});
}
});
}
2022-01-13 05:30:26 +01:00
export interface DatabaseDump {
name: string;
stores: { [s: string]: any };
version: string;
2022-01-13 05:30:26 +01:00
}
async function recoverFromDump(
db: IDBDatabase,
dump: DatabaseDump,
): Promise<void> {
2022-01-13 05:30:26 +01:00
return new Promise((resolve, reject) => {
const tx = db.transaction(Array.from(db.objectStoreNames), "readwrite");
tx.addEventListener("complete", () => {
2022-09-13 18:39:25 +02:00
resolve();
2022-01-13 05:30:26 +01:00
});
for (let i = 0; i < db.objectStoreNames.length; i++) {
const name = db.objectStoreNames[i];
const storeDump = dump.stores[name];
if (!storeDump) continue;
Object.keys(storeDump).forEach(async (key) => {
const value = storeDump[key];
2022-01-13 05:30:26 +01:00
if (!value) return;
tx.objectStore(name).put(value);
});
2022-01-13 05:30:26 +01:00
}
2022-04-29 18:16:29 +02:00
tx.commit();
});
2022-09-13 18:39:25 +02:00
}
export async function importDb(db: IDBDatabase, object: any): Promise<void> {
if ("name" in object && "stores" in object && "version" in object) {
// looks like a database dump
const dump = object as DatabaseDump;
2022-09-13 18:39:25 +02:00
return recoverFromDump(db, dump);
}
if ("databases" in object && "$types" in object) {
// looks like a IDBDatabase
const someDatabase = object.databases;
if (TALER_META_DB_NAME in someDatabase) {
//looks like a taler database
const currentMainDbValue =
someDatabase[TALER_META_DB_NAME].objectStores.metaConfig.records[0]
.value.value;
2022-09-13 18:39:25 +02:00
if (currentMainDbValue !== TALER_DB_NAME) {
console.log("not the current database version");
2022-09-13 18:39:25 +02:00
}
const talerDb = someDatabase[currentMainDbValue];
const objectStoreNames = Object.keys(talerDb.objectStores);
const dump: DatabaseDump = {
name: talerDb.schema.databaseName,
version: talerDb.schema.databaseVersion,
stores: {},
};
2022-09-13 18:39:25 +02:00
for (let i = 0; i < objectStoreNames.length; i++) {
const name = objectStoreNames[i];
const storeDump = {} as { [s: string]: any };
dump.stores[name] = storeDump;
talerDb.objectStores[name].records.map((r: any) => {
const pkey = r.primaryKey;
2022-11-22 19:15:40 +01:00
const key =
typeof pkey === "string" || typeof pkey === "number"
? pkey
: pkey.join(",");
2022-09-13 18:39:25 +02:00
storeDump[key] = r.value;
});
2022-09-13 18:39:25 +02:00
}
return recoverFromDump(db, dump);
}
}
throw Error("could not import database");
2022-01-13 05:30:26 +01:00
}
2023-01-11 14:19:24 +01:00
export interface FixupDescription {
name: string;
fn(tx: GetReadWriteAccess<typeof WalletStoresV1>): Promise<void>;
}
/**
* Manual migrations between minor versions of the DB schema.
*/
export const walletDbFixups: FixupDescription[] = [
{
name: "RefreshGroupRecord_currency",
async fn(tx): Promise<void> {
await tx.refreshGroups.iter().forEachAsync(async (rg) => {
if (rg.currency) {
return;
}
// Empty refresh group without input coin, delete it!
if (rg.inputPerCoin.length === 0) {
await tx.refreshGroups.delete(rg.refreshGroupId);
return;
}
rg.currency = Amounts.parseOrThrow(rg.inputPerCoin[0]).currency;
await tx.refreshGroups.put(rg);
});
},
},
2023-01-15 21:48:41 +01:00
{
name: "DepositGroupRecord_transactionPerCoin",
async fn(tx): Promise<void> {
await tx.depositGroups.iter().forEachAsync(async (dg) => {
if (dg.transactionPerCoin) {
return;
}
dg.transactionPerCoin = dg.depositedPerCoin.map(
(c) => TransactionStatus.Unknown,
);
await tx.depositGroups.put(dg);
});
},
},
2023-01-11 14:19:24 +01:00
];
const logger = new Logger("db.ts");
export async function applyFixups(
db: DbAccess<typeof WalletStoresV1>,
): Promise<void> {
await db.mktxAll().runReadWrite(async (tx) => {
for (const fixupInstruction of walletDbFixups) {
const fixupRecord = await tx.fixups.get(fixupInstruction.name);
if (fixupRecord) {
return;
}
logger.info(`applying DB fixup ${fixupInstruction.name}`);
await fixupInstruction.fn(tx);
await tx.fixups.put({
fixupName: fixupInstruction.name,
});
2023-01-11 14:19:24 +01:00
}
});
}
function upgradeFromStoreMap(
storeMap: any,
db: IDBDatabase,
oldVersion: number,
newVersion: number,
upgradeTransaction: IDBTransaction,
): void {
if (oldVersion === 0) {
for (const n in storeMap) {
const swi: StoreWithIndexes<
any,
StoreDescriptor<unknown>,
any
> = storeMap[n];
const storeDesc: StoreDescriptor<unknown> = swi.store;
const s = db.createObjectStore(swi.storeName, {
autoIncrement: storeDesc.autoIncrement,
keyPath: storeDesc.keyPath,
});
for (const indexName in swi.indexMap as any) {
const indexDesc: IndexDescriptor = swi.indexMap[indexName];
s.createIndex(indexDesc.name, indexDesc.keyPath, {
multiEntry: indexDesc.multiEntry,
unique: indexDesc.unique,
});
}
}
return;
}
if (oldVersion === newVersion) {
return;
}
logger.info(`upgrading database from ${oldVersion} to ${newVersion}`);
for (const n in storeMap) {
const swi: StoreWithIndexes<any, StoreDescriptor<unknown>, any> = storeMap[
n
];
const storeDesc: StoreDescriptor<unknown> = swi.store;
const storeAddedVersion = storeDesc.versionAdded ?? 0;
if (storeAddedVersion <= oldVersion) {
continue;
}
let s: IDBObjectStore;
try {
s = db.createObjectStore(swi.storeName, {
autoIncrement: storeDesc.autoIncrement,
keyPath: storeDesc.keyPath,
});
} catch (e) {
const moreInfo = e instanceof Error ? ` Reason: ${e.message}` : "";
throw Error(
`Migration failed. Could not create store ${swi.storeName}.${moreInfo}`,
);
}
2023-01-11 14:19:24 +01:00
for (const indexName in swi.indexMap as any) {
const indexDesc: IndexDescriptor = swi.indexMap[indexName];
const indexAddedVersion = indexDesc.versionAdded ?? 0;
if (indexAddedVersion <= oldVersion) {
continue;
}
try {
s.createIndex(indexDesc.name, indexDesc.keyPath, {
multiEntry: indexDesc.multiEntry,
unique: indexDesc.unique,
});
} catch (e) {
const moreInfo = e instanceof Error ? ` Reason: ${e.message}` : "";
throw Error(
`Migration failed. Could not create index ${indexDesc.name}/${indexDesc.keyPath}.${moreInfo}`,
);
}
2023-01-11 14:19:24 +01:00
}
}
}
function promiseFromTransaction(transaction: IDBTransaction): Promise<void> {
return new Promise<void>((resolve, reject) => {
transaction.oncomplete = () => {
resolve();
};
transaction.onerror = () => {
reject();
};
});
}
/**
* Purge all data in the given database.
*/
export function clearDatabase(db: IDBDatabase): Promise<void> {
// db.objectStoreNames is a DOMStringList, so we need to convert
let stores: string[] = [];
for (let i = 0; i < db.objectStoreNames.length; i++) {
stores.push(db.objectStoreNames[i]);
}
const tx = db.transaction(stores, "readwrite");
for (const store of stores) {
tx.objectStore(store).clear();
}
return promiseFromTransaction(tx);
}
function onTalerDbUpgradeNeeded(
db: IDBDatabase,
oldVersion: number,
newVersion: number,
upgradeTransaction: IDBTransaction,
) {
upgradeFromStoreMap(
WalletStoresV1,
db,
oldVersion,
newVersion,
upgradeTransaction,
);
}
function onMetaDbUpgradeNeeded(
db: IDBDatabase,
oldVersion: number,
newVersion: number,
upgradeTransaction: IDBTransaction,
) {
upgradeFromStoreMap(
walletMetadataStore,
db,
oldVersion,
newVersion,
upgradeTransaction,
);
}
/**
* Return a promise that resolves
* to the taler wallet db.
*/
export async function openTalerDatabase(
idbFactory: IDBFactory,
onVersionChange: () => void,
): Promise<DbAccess<typeof WalletStoresV1>> {
const metaDbHandle = await openDatabase(
idbFactory,
TALER_META_DB_NAME,
1,
() => {},
onMetaDbUpgradeNeeded,
);
const metaDb = new DbAccess(metaDbHandle, walletMetadataStore);
let currentMainVersion: string | undefined;
await metaDb
.mktx((stores) => [stores.metaConfig])
.runReadWrite(async (tx) => {
const dbVersionRecord = await tx.metaConfig.get(CURRENT_DB_CONFIG_KEY);
if (!dbVersionRecord) {
currentMainVersion = TALER_DB_NAME;
await tx.metaConfig.put({
key: CURRENT_DB_CONFIG_KEY,
value: TALER_DB_NAME,
});
} else {
currentMainVersion = dbVersionRecord.value;
}
});
if (currentMainVersion !== TALER_DB_NAME) {
switch (currentMainVersion) {
case "taler-wallet-main-v2":
case "taler-wallet-main-v3":
case "taler-wallet-main-v4": // temporary, we might migrate v4 later
case "taler-wallet-main-v5":
case "taler-wallet-main-v6":
case "taler-wallet-main-v7":
case "taler-wallet-main-v8":
// We consider this a pre-release
// development version, no migration is done.
await metaDb
.mktx((stores) => [stores.metaConfig])
.runReadWrite(async (tx) => {
await tx.metaConfig.put({
key: CURRENT_DB_CONFIG_KEY,
value: TALER_DB_NAME,
});
});
break;
default:
throw Error(
`major migration from database major=${currentMainVersion} not supported`,
);
}
}
const mainDbHandle = await openDatabase(
idbFactory,
TALER_DB_NAME,
WALLET_DB_MINOR_VERSION,
onVersionChange,
onTalerDbUpgradeNeeded,
);
const handle = new DbAccess(mainDbHandle, WalletStoresV1);
await applyFixups(handle);
return handle;
}
export async function deleteTalerDatabase(
idbFactory: IDBFactory,
): Promise<void> {
return new Promise((resolve, reject) => {
const req = idbFactory.deleteDatabase(TALER_DB_NAME);
req.onerror = () => reject(req.error);
req.onsuccess = () => resolve();
});
}