UNPKG

chaingate

Version:

A complete TypeScript library for connecting to and making transactions on different blockchains

92 lines 3.69 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WalletEncryption = exports.EncodingError = exports.WalletIncorrectPassword = exports.WalletIsNotEncrypted = void 0; const Encrypted_1 = require("./Encrypted"); class WalletIsNotEncrypted extends Error { constructor() { super('Cannot serialize an unencrypted wallet. Initialize the wallet with encryption settings using ' + '`{ encrypt: { password: "yourPassword", askForPassword } }`, where:\n' + '- `password` is your encryption string\n' + '- `askForPassword` is the interactive password prompt function'); if (Error.captureStackTrace) Error.captureStackTrace(this, WalletIsNotEncrypted); this.name = this.constructor.name; } } exports.WalletIsNotEncrypted = WalletIsNotEncrypted; class WalletIncorrectPassword extends Error { constructor() { super('Password for the wallet is incorrect'); if (Error.captureStackTrace) Error.captureStackTrace(this, WalletIncorrectPassword); this.name = this.constructor.name; } } exports.WalletIncorrectPassword = WalletIncorrectPassword; class EncodingError extends Error { constructor(message) { super(message); if (Error.captureStackTrace) Error.captureStackTrace(this, EncodingError); this.name = this.constructor.name; } } exports.EncodingError = EncodingError; class WalletEncryption { askForPassword; _secret; warnAboutUnencrypted = false; get isEncrypted() { return this._secret instanceof Encrypted_1.Encrypted; } constructor(secret, askForPassword) { this._secret = secret; this.askForPassword = askForPassword; } async encrypt(password) { if (this._secret instanceof Encrypted_1.Encrypted) throw new Error('Wallet is already encrypted'); this._secret = await Encrypted_1.Encrypted.encrypt(this._secret, password); } getSecret() { return this._secret; } async getSecretDecrypted() { if (this._secret instanceof Encrypted_1.Encrypted) { if (!this.askForPassword) throw new Error('Asking for password function not defined'); else { let attempts = 0; // eslint-disable-next-line no-constant-condition let encrypted; while (!encrypted) { const password = await this.askForPassword(attempts, () => { throw new WalletIncorrectPassword(); }); try { encrypted = await Encrypted_1.Encrypted.decrypt(this._secret, password); } catch (e) { if (e instanceof Encrypted_1.IncorrectPassword) attempts++; else throw e; } } return encrypted; } } else { if (this.warnAboutUnencrypted) { console.warn('WARNING: You are using an in-memory unencrypted wallet. ' + 'This may be acceptable in certain secure backend environments, ' + 'but can pose a security risk otherwise. ' + 'To disable this warning, set { warningAboutUnencrypted: false } during wallet creation.'); this.warnAboutUnencrypted = false; } return this._secret; } } } exports.WalletEncryption = WalletEncryption; //# sourceMappingURL=WalletEncryption.js.map