"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.InMemorySigner = exports.VERSION = void 0;
/**
 * @packageDocumentation
 * @module @taquito/signer
 */
var libsodium_wrappers_1 = require("libsodium-wrappers");
var utils_1 = require("@taquito/utils");
var typedarray_to_buffer_1 = require("typedarray-to-buffer");
var ed_key_1 = require("./ed-key");
var ec_key_1 = require("./ec-key");
var pbkdf2_1 = require("pbkdf2");
var bip39_1 = require("bip39");
__exportStar(require("./import-key"), exports);
var version_1 = require("./version");
Object.defineProperty(exports, "VERSION", { enumerable: true, get: function () { return version_1.VERSION; } });
/**
 * @description A local implementation of the signer. Will represent a Tezos account and be able to produce signature in its behalf
 *
 * @warn If running in production and dealing with tokens that have real value, it is strongly recommended to use a HSM backed signer so that private key material is not stored in memory or on disk
 *
 * @warn Calling this constructor directly is discouraged as it do not await for sodium library to be loaded.
 *
 * Consider doing:
 *
 * ```const sodium = require('libsodium-wrappers'); await sodium.ready;```
 *
 * The recommended usage is to use InMemorySigner.fromSecretKey('edsk', 'passphrase')
 */
var InMemorySigner = /** @class */ (function () {
    /**
     *
     * @param key Encoded private key
     * @param passphrase Passphrase to decrypt the private key if it is encrypted
     *
     */
    function InMemorySigner(key, passphrase) {
        var encrypted = key.substring(2, 3) === 'e';
        var decrypt = function (k) { return k; };
        if (encrypted) {
            if (!passphrase) {
                throw new Error('Encrypted key provided without a passphrase.');
            }
            decrypt = function (constructedKey) {
                var salt = typedarray_to_buffer_1.default(constructedKey.slice(0, 8));
                var encryptedSk = constructedKey.slice(8);
                var encryptionKey = pbkdf2_1.default.pbkdf2Sync(passphrase, salt, 32768, 32, 'sha512');
                return libsodium_wrappers_1.default.crypto_secretbox_open_easy(new Uint8Array(encryptedSk), new Uint8Array(24), new Uint8Array(encryptionKey));
            };
        }
        switch (key.substr(0, 4)) {
            case 'edes':
            case 'edsk':
                this._key = new ed_key_1.Tz1(key, encrypted, decrypt);
                break;
            case 'spsk':
            case 'spes':
                this._key = new ec_key_1.Tz2(key, encrypted, decrypt);
                break;
            case 'p2sk':
            case 'p2es':
                this._key = new ec_key_1.Tz3(key, encrypted, decrypt);
                break;
            default:
                throw new Error('Unsupported key type');
        }
    }
    InMemorySigner.fromFundraiser = function (email, password, mnemonic) {
        var seed = bip39_1.mnemonicToSeedSync(mnemonic, "" + email + password);
        var key = utils_1.b58cencode(seed.slice(0, 32), utils_1.prefix.edsk2);
        return new InMemorySigner(key);
    };
    InMemorySigner.fromSecretKey = function (key, passphrase) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, libsodium_wrappers_1.default.ready];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, new InMemorySigner(key, passphrase)];
                }
            });
        });
    };
    /**
     *
     * @param bytes Bytes to sign
     * @param watermark Watermark to append to the bytes
     */
    InMemorySigner.prototype.sign = function (bytes, watermark) {
        return __awaiter(this, void 0, void 0, function () {
            var bb, bytesHash;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        bb = utils_1.hex2buf(bytes);
                        if (typeof watermark !== 'undefined') {
                            bb = utils_1.mergebuf(watermark, bb);
                        }
                        // Ensure sodium is ready before calling crypto_generichash otherwise the function do not exists
                        return [4 /*yield*/, libsodium_wrappers_1.default.ready];
                    case 1:
                        // Ensure sodium is ready before calling crypto_generichash otherwise the function do not exists
                        _a.sent();
                        bytesHash = typedarray_to_buffer_1.default(libsodium_wrappers_1.default.crypto_generichash(32, bb));
                        return [2 /*return*/, this._key.sign(bytes, bytesHash)];
                }
            });
        });
    };
    /**
     * @returns Encoded public key
     */
    InMemorySigner.prototype.publicKey = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this._key.publicKey()];
            });
        });
    };
    /**
     * @returns Encoded public key hash
     */
    InMemorySigner.prototype.publicKeyHash = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this._key.publicKeyHash()];
            });
        });
    };
    /**
     * @returns Encoded private key
     */
    InMemorySigner.prototype.secretKey = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this._key.secretKey()];
            });
        });
    };
    return InMemorySigner;
}());
exports.InMemorySigner = InMemorySigner;
//# sourceMappingURL=taquito-signer.js.map