{"version":3,"sources":["../src/keys.ts","../src/signing.ts","../src/pem.ts","../src/crypto-provider.ts","../src/slip10-ed25519.ts","../src/hd-wallet.ts","../src/keystore.ts"],"names":["hexEncode","hexDecode","ed2","bech32Encode","sha512"],"mappings":";;;;;;;;;;;;AAOG,EAAA,CAAA,GAAA,CAAI,UAAA,GAAa,IAAI,CAAA,KAAM,MAAA,CAAU,OAAI,WAAA,CAAY,GAAG,CAAC,CAAC,CAAA;AAyBtD,IAAM,cAAA,GAAN,MAAM,eAAA,CAAqC;AAAA,EAChD,YAA4B,KAAA,EAAmB;AAAnB,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAC1B,IAAA,IAAI,KAAA,CAAM,WAAW,EAAA,EAAI;AACvB,MAAA,MAAM,IAAI,MAAM,8BAA8B,CAAA;AAAA,IAChD;AAAA,EACF;AAAA,EAEA,IAAI,GAAA,GAAc;AAChB,IAAA,OAAO,KAAK,KAAA,EAAM;AAAA,EACpB;AAAA,EAEA,KAAA,GAAgB;AACd,IAAA,OAAO,SAAA,CAAU,KAAK,KAAK,CAAA;AAAA,EAC7B;AAAA,EAEA,OAAO,QAAQ,GAAA,EAA6B;AAC1C,IAAA,OAAO,IAAI,eAAA,CAAe,SAAA,CAAU,GAAG,CAAC,CAAA;AAAA,EAC1C;AAAA,EAEA,OAAO,UAAU,KAAA,EAAmC;AAClD,IAAA,OAAO,IAAI,gBAAe,KAAK,CAAA;AAAA,EACjC;AACF;AA0BO,IAAM,aAAA,GAAN,MAAM,cAAA,CAAmC;AAAA,EAC9C,YAA4B,KAAA,EAAmB;AAAnB,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAC1B,IAAA,IAAI,KAAA,CAAM,WAAW,EAAA,EAAI;AACvB,MAAA,MAAM,IAAI,MAAM,6BAA6B,CAAA;AAAA,IAC/C;AAAA,EACF;AAAA,EAEA,IAAI,GAAA,GAAc;AAChB,IAAA,OAAO,KAAK,KAAA,EAAM;AAAA,EACpB;AAAA,EAEA,KA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;AACF,IAAA,MAAM,eAAA,CAAgB,UAAU,QAAQ,CAAA;AACxC,IAAA,OAAO,IAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF","file":"index.mjs","sourcesContent":["import * as ed from '@noble/ed25519'\nimport { sha512 } from '@noble/hashes/sha2'\n\nimport { hexEncode, hexDecode, bech32Encode } from '@klever/connect-encoding'\nimport type { KeyPair, PrivateKey, PublicKey } from './types'\n\n// Configure noble-ed25519 to use sha512\ned.etc.sha512Sync = (...m) => sha512(ed.etc.concatBytes(...m))\n\n/**\n * Implementation of a private key using Ed25519 cryptography.\n *\n * @remarks\n * This class represents a 32-byte Ed25519 private key used for signing transactions\n * and messages on the Klever blockchain.\n *\n * SECURITY WARNING: Never expose private keys in logs, network requests, or insecure storage.\n * Private keys should be stored securely (encrypted or in hardware wallets) and never\n * transmitted over insecure channels.\n *\n * @example\n * ```typescript\n * // Create from hex string\n * const privateKey = PrivateKeyImpl.fromHex('a1b2c3...')\n *\n * // Create from bytes\n * const privateKey = PrivateKeyImpl.fromBytes(new Uint8Array(32))\n *\n * // Convert to hex\n * const hex = privateKey.toHex()\n * ```\n */\nexport class PrivateKeyImpl implements PrivateKey {\n  constructor(public readonly bytes: Uint8Array) {\n    if (bytes.length !== 32) {\n      throw new Error('Private key must be 32 bytes')\n    }\n  }\n\n  get hex(): string {\n    return this.toHex()\n  }\n\n  toHex(): string {\n    return hexEncode(this.bytes)\n  }\n\n  static fromHex(hex: string): PrivateKeyImpl {\n    return new PrivateKeyImpl(hexDecode(hex))\n  }\n\n  static fromBytes(bytes: Uint8Array): PrivateKeyImpl {\n    return new PrivateKeyImpl(bytes)\n  }\n}\n\n/**\n * Implementation of a public key using Ed25519 cryptography.\n *\n * @remarks\n * This class represents a 32-byte Ed25519 public key derived from a private key.\n * Public keys are used to verify signatures and can be safely shared.\n * They can also be converted to Klever blockchain addresses.\n *\n * @example\n * ```typescript\n * // Create from hex string\n * const publicKey = PublicKeyImpl.fromHex('a1b2c3...')\n *\n * // Create from bytes\n * const publicKey = PublicKeyImpl.fromBytes(new Uint8Array(32))\n *\n * // Convert to Klever address (bech32 format)\n * const address = publicKey.toAddress()\n * // Returns: 'klv1...'\n *\n * // Convert to hex\n * const hex = publicKey.toHex()\n * ```\n */\nexport class PublicKeyImpl implements PublicKey {\n  constructor(public readonly bytes: Uint8Array) {\n    if (bytes.length !== 32) {\n      throw new Error('Public key must be 32 bytes')\n    }\n  }\n\n  get hex(): string {\n    return this.toHex()\n  }\n\n  toHex(): string {\n    return hexEncode(this.bytes)\n  }\n\n  toAddress(): string {\n    return bech32Encode(this.bytes)\n  }\n\n  static fromHex(hex: string): PublicKeyImpl {\n    return new PublicKeyImpl(hexDecode(hex))\n  }\n\n  static fromBytes(bytes: Uint8Array): PublicKeyImpl {\n    return new PublicKeyImpl(bytes)\n  }\n}\n\n/**\n * Generates a new Ed25519 key pair asynchronously using cryptographically secure random bytes.\n *\n * @remarks\n * This function uses the noble-ed25519 library to generate a secure random private key\n * and derives the corresponding public key. The asynchronous version is recommended\n * for better performance in environments that support it.\n *\n * SECURITY WARNING: The generated private key must be stored securely. Never expose\n * it in logs, network requests, or insecure storage. Consider using hardware wallets\n * or encrypted storage for production applications.\n *\n * @returns A promise that resolves to a KeyPair object containing both private and public keys\n *\n * @example\n * ```typescript\n * // Generate a new key pair\n * const keyPair = await generateKeyPair()\n *\n * // Access the keys\n * const privateKeyHex = keyPair.privateKey.toHex()\n * const publicKeyHex = keyPair.publicKey.toHex()\n * const address = keyPair.publicKey.toAddress()\n *\n * console.log('Address:', address)\n * // Prints: klv1...\n * ```\n */\nexport async function generateKeyPair(): Promise<KeyPair> {\n  const privateKeyBytes = ed.utils.randomPrivateKey()\n  const publicKeyBytes = await ed.getPublicKeyAsync(privateKeyBytes)\n\n  return {\n    privateKey: new PrivateKeyImpl(privateKeyBytes),\n    publicKey: new PublicKeyImpl(publicKeyBytes),\n  }\n}\n\n/**\n * Generates a new Ed25519 key pair synchronously using cryptographically secure random bytes.\n *\n * @remarks\n * This function uses the noble-ed25519 library to generate a secure random private key\n * and derives the corresponding public key. The synchronous version is provided for\n * environments that don't support async operations, but the async version is generally\n * preferred for better performance.\n *\n * SECURITY WARNING: The generated private key must be stored securely. Never expose\n * it in logs, network requests, or insecure storage. Consider using hardware wallets\n * or encrypted storage for production applications.\n *\n * @returns A KeyPair object containing both private and public keys\n *\n * @example\n * ```typescript\n * // Generate a new key pair synchronously\n * const keyPair = generateKeyPairSync()\n *\n * // Access the keys\n * const privateKeyHex = keyPair.privateKey.toHex()\n * const publicKeyHex = keyPair.publicKey.toHex()\n * const address = keyPair.publicKey.toAddress()\n *\n * console.log('Address:', address)\n * // Prints: klv1...\n * ```\n */\nexport function generateKeyPairSync(): KeyPair {\n  const privateKeyBytes = ed.utils.randomPrivateKey()\n  const publicKeyBytes = ed.getPublicKey(privateKeyBytes)\n\n  return {\n    privateKey: new PrivateKeyImpl(privateKeyBytes),\n    publicKey: new PublicKeyImpl(publicKeyBytes),\n  }\n}\n\n/**\n * Derives the public key from a private key asynchronously.\n *\n * @remarks\n * This function uses Ed25519 elliptic curve cryptography to derive the public key\n * from the given private key. The public key can be safely shared and is used for\n * signature verification and address generation.\n *\n * @param privateKey - The 32-byte private key as a Uint8Array\n * @returns A promise that resolves to the 32-byte public key as a Uint8Array\n *\n * @throws Error if the private key is invalid or not 32 bytes\n *\n * @example\n * ```typescript\n * const privateKeyBytes = new Uint8Array(32) // Your private key bytes\n * const publicKeyBytes = await getPublicKeyFromPrivate(privateKeyBytes)\n *\n * // Convert to PublicKeyImpl for additional methods\n * const publicKey = PublicKeyImpl.fromBytes(publicKeyBytes)\n * const address = publicKey.toAddress()\n * ```\n */\nexport async function getPublicKeyFromPrivate(privateKey: Uint8Array): Promise<Uint8Array> {\n  return ed.getPublicKeyAsync(privateKey)\n}\n\n/**\n * Derives the public key from a private key synchronously.\n *\n * @remarks\n * This function uses Ed25519 elliptic curve cryptography to derive the public key\n * from the given private key. The synchronous version is provided for environments\n * that don't support async operations, but the async version is generally preferred.\n *\n * @param privateKey - The 32-byte private key as a Uint8Array\n * @returns The 32-byte public key as a Uint8Array\n *\n * @throws Error if the private key is invalid or not 32 bytes\n *\n * @example\n * ```typescript\n * const privateKeyBytes = new Uint8Array(32) // Your private key bytes\n * const publicKeyBytes = getPublicKeyFromPrivateSync(privateKeyBytes)\n *\n * // Convert to PublicKeyImpl for additional methods\n * const publicKey = PublicKeyImpl.fromBytes(publicKeyBytes)\n * const address = publicKey.toAddress()\n * ```\n */\nexport function getPublicKeyFromPrivateSync(privateKey: Uint8Array): Uint8Array {\n  return ed.getPublicKey(privateKey)\n}\n","import * as ed from '@noble/ed25519'\nimport { keccak_256 } from '@noble/hashes/sha3'\n\nimport { hexEncode, hexDecode, base64Encode, base64Decode } from '@klever/connect-encoding'\nimport type { Signature } from './types'\n\n/**\n * Implementation of a cryptographic signature using Ed25519.\n *\n * @remarks\n * This class represents a 64-byte Ed25519 signature generated by signing a message\n * with a private key. Signatures can be verified using the corresponding public key\n * to ensure message authenticity and integrity.\n *\n * Signatures can be encoded in multiple formats:\n * - Hex (hexadecimal string)\n * - Base64 (base64 string)\n * - Raw bytes (Uint8Array)\n *\n * @example\n * ```typescript\n * // Create from hex string\n * const signature = SignatureImpl.fromHex('a1b2c3...')\n *\n * // Create from base64 string\n * const signature = SignatureImpl.fromBase64('YWJjZGVm...')\n *\n * // Create from bytes\n * const signature = SignatureImpl.fromBytes(new Uint8Array(64))\n *\n * // Convert to different formats\n * const hex = signature.toHex()\n * const base64 = signature.toBase64()\n * const bytes = signature.bytes\n * ```\n */\nexport class SignatureImpl implements Signature {\n  constructor(public readonly bytes: Uint8Array) {\n    if (bytes.length !== 64) {\n      throw new Error('Signature must be 64 bytes')\n    }\n  }\n\n  get hex(): string {\n    return this.toHex()\n  }\n\n  toHex(): string {\n    return hexEncode(this.bytes)\n  }\n\n  toBase64(): string {\n    return base64Encode(this.bytes)\n  }\n\n  static fromHex(hex: string): SignatureImpl {\n    return new SignatureImpl(hexDecode(hex))\n  }\n\n  static fromBase64(base64: string): SignatureImpl {\n    return new SignatureImpl(base64Decode(base64))\n  }\n\n  static fromBytes(bytes: Uint8Array): SignatureImpl {\n    return new SignatureImpl(bytes)\n  }\n}\n\n/**\n * Signs a message asynchronously using Ed25519 cryptography.\n *\n * @remarks\n * This function creates a cryptographic signature that proves the message was signed\n * by the holder of the private key. The signature can be verified by anyone with the\n * corresponding public key to ensure message authenticity and integrity.\n *\n * SECURITY WARNING: Never expose the private key used for signing. Ensure the private\n * key is stored securely and never transmitted over insecure channels.\n *\n * @param message - The message to sign as a Uint8Array (often a transaction hash)\n * @param privateKey - The 32-byte private key used for signing\n * @returns A promise that resolves to a 64-byte signature as a Uint8Array\n *\n * @throws Error if the private key is invalid or signing fails\n *\n * @example\n * ```typescript\n * const message = new TextEncoder().encode('Hello, Klever!')\n * const privateKey = new Uint8Array(32) // Your private key bytes\n *\n * const signatureBytes = await signMessage(message, privateKey)\n *\n * // Convert to SignatureImpl for additional methods\n * const signature = SignatureImpl.fromBytes(signatureBytes)\n * console.log('Signature (hex):', signature.toHex())\n * console.log('Signature (base64):', signature.toBase64())\n * ```\n */\nexport async function signMessage(\n  message: Uint8Array,\n  privateKey: Uint8Array,\n): Promise<Uint8Array> {\n  return ed.signAsync(message, privateKey)\n}\n\n/**\n * Signs a message synchronously using Ed25519 cryptography.\n *\n * @remarks\n * This function creates a cryptographic signature that proves the message was signed\n * by the holder of the private key. The signature can be verified by anyone with the\n * corresponding public key to ensure message authenticity and integrity.\n *\n * The synchronous version is provided for environments that don't support async\n * operations, but the async version is generally preferred for better performance.\n *\n * SECURITY WARNING: Never expose the private key used for signing. Ensure the private\n * key is stored securely and never transmitted over insecure channels.\n *\n * @param message - The message to sign as a Uint8Array (often a transaction hash)\n * @param privateKey - The 32-byte private key used for signing\n * @returns A 64-byte signature as a Uint8Array\n *\n * @throws Error if the private key is invalid or signing fails\n *\n * @example\n * ```typescript\n * const message = new TextEncoder().encode('Hello, Klever!')\n * const privateKey = new Uint8Array(32) // Your private key bytes\n *\n * const signatureBytes = signMessageSync(message, privateKey)\n *\n * // Convert to SignatureImpl for additional methods\n * const signature = SignatureImpl.fromBytes(signatureBytes)\n * console.log('Signature (hex):', signature.toHex())\n * ```\n */\nexport function signMessageSync(message: Uint8Array, privateKey: Uint8Array): Uint8Array {\n  return ed.sign(message, privateKey)\n}\n\n/**\n * Verifies a signature asynchronously using Ed25519 cryptography.\n *\n * @remarks\n * This function verifies that a signature was created by the holder of the private key\n * corresponding to the given public key. It ensures message authenticity and integrity.\n *\n * Returns true if the signature is valid, false otherwise. This function never throws\n * on invalid signatures - it returns false instead, making it safe to use in validation logic.\n *\n * @param message - The original message that was signed\n * @param signature - The 64-byte signature to verify\n * @param publicKey - The 32-byte public key used for verification\n * @returns A promise that resolves to true if the signature is valid, false otherwise\n *\n * @example\n * ```typescript\n * const message = new TextEncoder().encode('Hello, Klever!')\n * const signatureBytes = new Uint8Array(64) // Signature from signMessage\n * const publicKeyBytes = new Uint8Array(32) // Public key\n *\n * const isValid = await verifySignature(message, signatureBytes, publicKeyBytes)\n *\n * if (isValid) {\n *   console.log('Signature is valid!')\n * } else {\n *   console.log('Invalid signature')\n * }\n * ```\n */\nexport async function verifySignature(\n  message: Uint8Array,\n  signature: Uint8Array,\n  publicKey: Uint8Array,\n): Promise<boolean> {\n  try {\n    return await ed.verifyAsync(signature, message, publicKey)\n  } catch {\n    return false\n  }\n}\n\n/**\n * Verifies a signature synchronously using Ed25519 cryptography.\n *\n * @remarks\n * This function verifies that a signature was created by the holder of the private key\n * corresponding to the given public key. It ensures message authenticity and integrity.\n *\n * The synchronous version is provided for environments that don't support async\n * operations, but the async version is generally preferred for better performance.\n *\n * Returns true if the signature is valid, false otherwise. This function never throws\n * on invalid signatures - it returns false instead, making it safe to use in validation logic.\n *\n * @param message - The original message that was signed\n * @param signature - The 64-byte signature to verify\n * @param publicKey - The 32-byte public key used for verification\n * @returns True if the signature is valid, false otherwise\n *\n * @example\n * ```typescript\n * const message = new TextEncoder().encode('Hello, Klever!')\n * const signatureBytes = new Uint8Array(64) // Signature from signMessageSync\n * const publicKeyBytes = new Uint8Array(32) // Public key\n *\n * const isValid = verifySignatureSync(message, signatureBytes, publicKeyBytes)\n *\n * if (isValid) {\n *   console.log('Signature is valid!')\n * } else {\n *   console.log('Invalid signature')\n * }\n * ```\n */\nexport function verifySignatureSync(\n  message: Uint8Array,\n  signature: Uint8Array,\n  publicKey: Uint8Array,\n): boolean {\n  try {\n    return ed.verify(signature, message, publicKey)\n  } catch {\n    return false\n  }\n}\n\n// KLV message prefix — mirrors the constant in kos-rs `KLV::prepare_message`.\nconst KLV_MESSAGE_PREFIX = '\\x17Klever Signed Message:\\n'\n\n/**\n * Prepares a plaintext message for KLV chain signature verification.\n *\n * @remarks\n * The Klever browser extension (kos-rs `KLV::prepare_message`) applies this\n * protocol before Ed25519-signing any message:\n *\n * 1. Prepend the 23-byte prefix `\"\\x17Klever Signed Message:\\n\"`\n * 2. Append the UTF-8 byte length of the message as an ASCII decimal string\n * 3. Append the UTF-8-encoded message bytes\n * 4. Return the keccak256 digest of the concatenated data\n *\n * Use the returned 32-byte hash as the `message` argument to `verifySignature`\n * whenever the signature was produced by `window.kleverWeb.signMessage` or\n * `BrowserWallet.signMessage` (extension mode).\n *\n * @param message - The original plaintext message string\n * @returns A 32-byte keccak256 digest ready for Ed25519 signature verification\n *\n * @example\n * ```typescript\n * const messageHash = prepareKlvMessage('Submit validation for contract klv1...')\n * const isValid = await verifySignature(messageHash, signatureBytes, publicKeyBytes)\n * ```\n */\nexport function prepareKlvMessage(message: string): Uint8Array {\n  const msgBytes = new TextEncoder().encode(message)\n  const prefix = new TextEncoder().encode(KLV_MESSAGE_PREFIX)\n  const length = new TextEncoder().encode(String(msgBytes.length))\n  const prepared = new Uint8Array(prefix.length + length.length + msgBytes.length)\n  prepared.set(prefix, 0)\n  prepared.set(length, prefix.length)\n  prepared.set(msgBytes, prefix.length + length.length)\n  return keccak_256(prepared)\n}\n\n/**\n * Verifies a message signature produced by the Klever browser extension.\n *\n * @remarks\n * Combines `prepareKlvMessage` and `verifySignature` into a single call.\n * Accepts the raw base64 or hex signature string returned by\n * `BrowserWallet.signMessage` / `window.kleverWeb.signMessage` and verifies it\n * against the signer's KLV address.\n *\n * @param message - The original plaintext message that was signed\n * @param signature - The 64-byte signature as a `Uint8Array`\n * @param publicKey - The signer's 32-byte Ed25519 public key\n * @returns A promise resolving to `true` if the signature is valid\n *\n * @example\n * ```typescript\n * import { cryptoProvider, verifyWalletSignedMessage } from '@klever/connect-crypto'\n *\n * const publicKey = await cryptoProvider.addressToBytes(walletAddress)\n * const sigBytes = Uint8Array.from(atob(signatureBase64), c => c.charCodeAt(0))\n * const isValid = await verifyWalletSignedMessage(message, sigBytes, publicKey)\n * ```\n */\nexport async function verifyWalletSignedMessage(\n  message: string,\n  signature: Uint8Array,\n  publicKey: Uint8Array,\n): Promise<boolean> {\n  return verifySignature(prepareKlvMessage(message), signature, publicKey)\n}\n","/**\n * PEM file utilities for loading and parsing private keys\n */\n\nconst PEM_HEADER_REGEX = /-----BEGIN (.+?)-----/\nconst PEM_FOOTER_REGEX = /-----END (.+?)-----/\nconst PRIVATE_KEY_HEADER = 'PRIVATE KEY for '\n\nexport interface PemBlock {\n  type: string\n  headers: Record<string, string>\n  bytes: Uint8Array\n}\n\nimport { bech32Encode, hexEncode, hexDecode } from '@klever/connect-encoding'\nimport { getPublicKeyFromPrivate } from './keys'\nimport type { LoadPemOptions } from './types'\n\n/**\n * Parses PEM blocks from string content.\n *\n * @remarks\n * This function extracts all PEM blocks from a string, handling both encrypted\n * and unencrypted blocks. It parses the PEM headers, base64 data, and converts\n * the content to bytes.\n *\n * @param content - The PEM file content as a string\n * @returns An array of parsed PEM blocks\n *\n * @throws Error if the PEM data is malformed or cannot be decoded\n *\n * @internal This is an internal function used by loadPrivateKeyFromPem\n */\nfunction parsePemBlocks(content: string): PemBlock[] {\n  const blocks: PemBlock[] = []\n  const lines = content.split('\\n').map((line) => line.trim())\n\n  let inBlock = false\n  let currentBlock: Partial<PemBlock> | null = null\n  let base64Data = ''\n\n  for (const line of lines) {\n    if (!line) continue\n\n    const headerMatch = line.match(PEM_HEADER_REGEX)\n    if (headerMatch) {\n      inBlock = true\n      currentBlock = {\n        type: headerMatch[1] || '',\n        headers: {},\n        bytes: new Uint8Array(),\n      }\n      base64Data = ''\n      continue\n    }\n\n    const footerMatch = line.match(PEM_FOOTER_REGEX)\n    if (footerMatch && inBlock && currentBlock) {\n      // Decode base64 data to get hex string\n      try {\n        const binaryString = atob(base64Data)\n        // The decoded base64 is actually a hex string, so convert it to string first\n        const hexString = binaryString\n        // Now decode the hex string to bytes\n        const bytes = hexDecode(hexString)\n        currentBlock.bytes = bytes\n        blocks.push(currentBlock as PemBlock)\n      } catch (error) {\n        throw new Error(`Invalid data in PEM block: ${String(error)}`, { cause: error })\n      }\n\n      inBlock = false\n      currentBlock = null\n      base64Data = ''\n      continue\n    }\n\n    if (inBlock && currentBlock) {\n      // Check for headers (e.g., DEK-Info)\n      if (line.includes(':')) {\n        const [key, value] = line.split(':', 2)\n        if (key && value && currentBlock.headers) {\n          currentBlock.headers[key.trim()] = value.trim()\n        }\n      } else {\n        // It's base64 data\n        base64Data += line\n      }\n    }\n  }\n\n  return blocks\n}\n\n/**\n * Checks if a PEM block is encrypted.\n *\n * @remarks\n * Determines if a PEM block is encrypted by checking for the presence of the\n * DEK-Info header, which indicates the encryption algorithm used.\n *\n * @param block - The PEM block to check\n * @returns True if the block is encrypted, false otherwise\n *\n * @example\n * ```typescript\n * const blocks = parsePemBlocks(pemContent)\n * const isEncrypted = isEncryptedPemBlock(blocks[0])\n *\n * if (isEncrypted) {\n *   console.log('This PEM file requires a password')\n * }\n * ```\n */\nexport function isEncryptedPemBlock(block: PemBlock): boolean {\n  return 'DEK-Info' in block.headers\n}\n\n/**\n * Decrypts an encrypted PEM block using AES-GCM encryption.\n *\n * @remarks\n * This function decrypts a PEM block that was encrypted using AES-GCM mode.\n * The decryption key is derived from the password using SHA-256.\n *\n * SECURITY WARNINGS:\n * - Use strong passwords for PEM encryption (minimum 12 characters, mix of letters, numbers, symbols)\n * - Incorrect passwords will result in decryption failure\n * - Never hardcode passwords in source code\n * - Store passwords securely (use environment variables, secure vaults, or password managers)\n *\n * @param block - The encrypted PEM block to decrypt\n * @param password - The password used to decrypt the block\n * @returns A promise that resolves to the decrypted PEM block\n *\n * @throws Error if the DEK-Info header is missing or invalid\n * @throws Error if the encryption mode is not supported (only AES-GCM is supported)\n * @throws Error if the data size is invalid\n * @throws Error if decryption fails (usually due to incorrect password)\n *\n * @internal This is an internal function used by loadPrivateKeyFromPem\n */\nasync function decryptPemBlock(block: PemBlock, password: string): Promise<PemBlock> {\n  const dekInfo = block.headers['DEK-Info']\n  if (!dekInfo) {\n    throw new Error('No DEK-Info header in encrypted block')\n  }\n\n  const [mode] = dekInfo.split(',')\n  if (mode !== 'AES-GCM') {\n    throw new Error(`Unsupported encryption mode: ${mode}`)\n  }\n\n  // Derive encryption key from password using the same method as Go\n  const encryptionKey = await getEncryptionKey(password)\n\n  // Import key for AES-GCM\n  // Cast to ArrayBuffer to satisfy SubtleCrypto type requirements\n  const key = await crypto.subtle.importKey(\n    'raw',\n    encryptionKey.buffer as ArrayBuffer,\n    { name: 'AES-GCM' },\n    false,\n    ['decrypt'],\n  )\n\n  // Extract nonce and ciphertext\n  const nonceSize = 12 // Standard GCM nonce size\n  if (block.bytes.length < nonceSize) {\n    throw new Error('Invalid data size')\n  }\n\n  const nonce = block.bytes.slice(0, nonceSize)\n  const ciphertext = block.bytes.slice(nonceSize)\n\n  try {\n    // Decrypt the data\n    const plaintext = await crypto.subtle.decrypt(\n      {\n        name: 'AES-GCM',\n        iv: nonce,\n      },\n      key,\n      ciphertext,\n    )\n\n    return {\n      type: block.type,\n      headers: {},\n      bytes: new Uint8Array(plaintext),\n    }\n  } catch (error) {\n    throw new Error(`Failed to decrypt PEM block: ${String(error)}`, { cause: error })\n  }\n}\n\n/**\n * Derives an encryption key from a password using SHA-256.\n *\n * @remarks\n * This function derives a 32-byte encryption key from a password using SHA-256 hashing.\n * It should match the Go implementation's getEncryptionKey function for compatibility.\n *\n * SECURITY WARNINGS:\n * - Use strong passwords (minimum 12 characters, mix of letters, numbers, and symbols)\n * - Passwords should not be reused across different systems\n * - Consider using a password manager to generate and store secure passwords\n * - This uses SHA-256 for key derivation; for new implementations, consider using\n *   PBKDF2, scrypt, or Argon2 for better security\n *\n * @param password - The password to derive the encryption key from\n * @returns A promise that resolves to a 32-byte encryption key\n *\n * @internal This is an internal function used by decryptPemBlock\n */\nasync function getEncryptionKey(password: string): Promise<Uint8Array> {\n  // Convert password to bytes\n  const encoder = new TextEncoder()\n  const passwordBytes = encoder.encode(password)\n\n  // Use SHA-256 to derive a 32-byte key (matching typical Go implementations)\n  const hash = await crypto.subtle.digest('SHA-256', passwordBytes)\n\n  return new Uint8Array(hash)\n}\n\n/**\n * Loads a private key from PEM file content with address verification.\n *\n * @remarks\n * This function parses PEM content and extracts the private key. It performs\n * address verification to ensure the private key in the PEM file actually\n * corresponds to the address claimed in the PEM header, preventing tampering\n * or mistakes in PEM file generation.\n *\n * For encrypted PEM files, a password must be provided. The function supports\n * multiple PEM blocks in a single file and allows selecting a specific block\n * by index.\n *\n * SECURITY WARNINGS:\n * - Use strong passwords for encrypted PEM files (minimum 12 characters, mix of letters, numbers, symbols)\n * - Store PEM files with restrictive permissions (e.g., 600 on Unix systems)\n * - Never transmit unencrypted PEM files over insecure channels\n * - Never commit PEM files to version control\n * - Consider using hardware wallets for production applications\n * - The private key is loaded into memory; ensure your application has appropriate\n *   security measures to protect memory from unauthorized access\n *\n * @param content - PEM file content as string\n * @param options - Loading options including password and key index\n * @returns A promise that resolves to an object containing the private key bytes and address\n *\n * @throws Error if no PEM blocks are found\n * @throws Error if the index is invalid or out of range\n * @throws Error if an encrypted key is encountered without a password\n * @throws Error if the block type is invalid (doesn't start with 'PRIVATE KEY for ')\n * @throws Error if the private key does not derive to the claimed address (security check)\n * @throws Error if decryption fails (usually due to incorrect password)\n *\n * @example\n * ```typescript\n * // Load encrypted PEM\n * const pemContent = '-----BEGIN PRIVATE KEY for klv1...-----\\n...'\n * const result = await loadPrivateKeyFromPem(pemContent, {\n *   password: 'your-secure-password',\n *   index: 0\n * })\n * console.log('Address:', result.address)\n * console.log('Private Key loaded successfully')\n *\n * // Load unencrypted PEM\n * const result2 = await loadPrivateKeyFromPem(pemContent)\n * ```\n */\nexport async function loadPrivateKeyFromPem(\n  content: string,\n  options: LoadPemOptions = {},\n): Promise<{ privateKey: Uint8Array; address: string }> {\n  const { password, index = 0 } = options\n\n  if (index < 0) {\n    throw new Error('Invalid key index')\n  }\n\n  const blocks = parsePemBlocks(content)\n\n  if (blocks.length === 0) {\n    throw new Error('No PEM blocks found in content')\n  }\n\n  if (index >= blocks.length) {\n    throw new Error(`Invalid index ${index}, only ${blocks.length} blocks found`)\n  }\n\n  let block = blocks[index]\n  if (!block) {\n    throw new Error(`Block at index ${index} not found`)\n  }\n\n  // Check if block is encrypted\n  if (isEncryptedPemBlock(block)) {\n    if (!password) {\n      throw new Error('Encrypted key, must provide password')\n    }\n    block = await decryptPemBlock(block, password)\n  }\n\n  // Validate block type\n  if (!block.type.startsWith(PRIVATE_KEY_HEADER)) {\n    throw new Error(\n      `Invalid block type, expected '${PRIVATE_KEY_HEADER}' prefix, got: ${block.type}`,\n    )\n  }\n\n  // Extract address from block type\n  const addressFromPem = block.type.substring(PRIVATE_KEY_HEADER.length)\n\n  const hexPK = hexEncode(block.bytes)\n  // if block bytes length = 64, get first 32bytes\n  if (block.bytes.length === 64) {\n    block.bytes = block.bytes.slice(0, 32)\n  }\n\n  // Verify that the private key corresponds to the address\n  const publicKeyBytes = await getPublicKeyFromPrivate(block.bytes)\n  const derivedAddress = bech32Encode(publicKeyBytes, 'klv')\n\n  if (derivedAddress !== addressFromPem) {\n    throw new Error(\n      `Address mismatch: PEM claims address ${addressFromPem} but private key derives to ${derivedAddress} ${hexPK}`,\n    )\n  }\n\n  return {\n    privateKey: block.bytes,\n    address: addressFromPem,\n  }\n}\n\n/**\n * Loads a private key from a PEM file on the filesystem (Node.js only).\n *\n * @remarks\n * This is a convenience wrapper that reads a PEM file from the filesystem and\n * loads the private key. This method is only available in Node.js environments.\n *\n * The function performs the same address verification as loadPrivateKeyFromPem\n * to ensure the private key corresponds to the claimed address.\n *\n * SECURITY WARNINGS:\n * - Store PEM files with restrictive permissions (e.g., 600 on Unix systems)\n * - Use strong passwords for encrypted PEM files (minimum 12 characters, mix of letters, numbers, symbols)\n * - Never commit PEM files to version control\n * - Never share PEM files over insecure channels (use encrypted transfer methods)\n * - Consider using hardware wallets for production applications\n * - Ensure the file path doesn't expose sensitive information in logs\n * - The private key is loaded into memory; ensure your application has appropriate\n *   security measures to protect memory from unauthorized access\n *\n * @param filePath - The path to the PEM file (absolute or relative)\n * @param options - Loading options including password and key index\n * @returns A promise that resolves to an object containing the private key bytes and address\n *\n * @throws Error if not in Node.js environment (browser context)\n * @throws Error if the file cannot be read\n * @throws Error if the PEM content is invalid (see loadPrivateKeyFromPem for details)\n *\n * @example\n * ```typescript\n * // Load encrypted PEM file\n * const result = await loadPrivateKeyFromPemFile('./wallet.pem', {\n *   password: 'your-secure-password'\n * })\n * console.log('Address:', result.address)\n *\n * // Load unencrypted PEM file\n * const result2 = await loadPrivateKeyFromPemFile('./wallet.pem')\n *\n * // Set appropriate file permissions (Unix/Linux/macOS)\n * // chmod 600 wallet.pem\n * ```\n */\nexport async function loadPrivateKeyFromPemFile(\n  filePath: string,\n  options: LoadPemOptions = {},\n): Promise<{ privateKey: Uint8Array; address: string }> {\n  // Check if we're in Node.js environment\n  if (typeof globalThis !== 'undefined' && 'window' in globalThis) {\n    throw new Error('File operations are only available in Node.js environment')\n  }\n\n  try {\n    // Dynamic import to avoid bundling fs in browser builds\n    const fs = await import('fs/promises')\n    const content = await fs.readFile(filePath, 'utf-8')\n    return loadPrivateKeyFromPem(content, options)\n  } catch (error) {\n    throw new Error(`Failed to read PEM file: ${String(error)}`, { cause: error })\n  }\n}\n","import { bech32Decode, bech32Encode } from '@klever/connect-encoding'\nimport {\n  PrivateKeyImpl,\n  PublicKeyImpl,\n  generateKeyPair as genKeyPair,\n  getPublicKeyFromPrivate,\n} from './keys'\nimport { loadPrivateKeyFromPem, loadPrivateKeyFromPemFile } from './pem'\nimport { SignatureImpl, signMessage as sign, verifySignature as verify } from './signing'\nimport type {\n  CryptoProvider,\n  KeyPair,\n  PrivateKey,\n  PublicKey,\n  Signature,\n  LoadPemOptions,\n} from './types'\n\n/**\n * Default implementation of the CryptoProvider interface for Klever blockchain.\n *\n * @remarks\n * This class provides a complete cryptographic provider implementation using Ed25519\n * for key generation, signing, and verification. It also handles address encoding/decoding\n * using bech32 format and supports PEM file operations for private key management.\n *\n * This provider is used throughout the Klever Connect SDK for all cryptographic operations\n * and can be replaced with custom implementations if needed (e.g., hardware wallet providers).\n *\n * SECURITY WARNING: This provider handles private keys in memory. For production applications,\n * consider using hardware wallets or secure enclaves for private key storage.\n *\n * @example\n * ```typescript\n * // Create a new provider instance\n * const provider = new DefaultCryptoProvider()\n *\n * // Generate a new key pair\n * const keyPair = await provider.generateKeyPair()\n * console.log('Address:', keyPair.publicKey.toAddress())\n *\n * // Import an existing private key\n * const privateKey = provider.importPrivateKey('your-private-key-hex')\n * const publicKey = await provider.getPublicKey(privateKey)\n *\n * // Sign a message\n * const message = new TextEncoder().encode('Hello, Klever!')\n * const signature = await provider.signMessage(message, privateKey)\n *\n * // Verify a signature\n * const isValid = await provider.verifySignature(message, signature, publicKey)\n * ```\n */\nexport class DefaultCryptoProvider implements CryptoProvider {\n  /**\n   * Generates a new Ed25519 key pair.\n   *\n   * @remarks\n   * Creates a new cryptographically secure key pair suitable for use on the Klever blockchain.\n   * The generated private key should be stored securely.\n   *\n   * SECURITY WARNING: Store the generated private key securely. Never expose it in logs,\n   * network requests, or insecure storage. Consider using hardware wallets or encrypted\n   * storage for production applications.\n   *\n   * @returns A promise that resolves to a KeyPair containing both private and public keys\n   *\n   * @example\n   * ```typescript\n   * const provider = new DefaultCryptoProvider()\n   * const keyPair = await provider.generateKeyPair()\n   *\n   * console.log('Private Key:', keyPair.privateKey.toHex())\n   * console.log('Public Key:', keyPair.publicKey.toHex())\n   * console.log('Address:', keyPair.publicKey.toAddress())\n   * ```\n   */\n  async generateKeyPair(): Promise<KeyPair> {\n    return genKeyPair()\n  }\n\n  /**\n   * Imports a private key from hex string or bytes.\n   *\n   * @remarks\n   * This method accepts private keys in two formats:\n   * - Hex string (with or without '0x' prefix)\n   * - Uint8Array of 32 bytes\n   *\n   * SECURITY WARNING: Never expose private keys in logs, network requests, or insecure storage.\n   * Ensure private keys are transmitted and stored securely.\n   *\n   * @param key - The private key as a hex string or Uint8Array\n   * @returns A PrivateKey instance\n   *\n   * @throws Error if the key is invalid or not 32 bytes\n   *\n   * @example\n   * ```typescript\n   * const provider = new DefaultCryptoProvider()\n   *\n   * // Import from hex string\n   * const privateKey1 = provider.importPrivateKey('a1b2c3...')\n   *\n   * // Import from hex string with 0x prefix\n   * const privateKey2 = provider.importPrivateKey('0xa1b2c3...')\n   *\n   * // Import from bytes\n   * const privateKey3 = provider.importPrivateKey(new Uint8Array(32))\n   * ```\n   */\n  importPrivateKey(key: string | Uint8Array): PrivateKey {\n    if (typeof key === 'string') {\n      // Remove any 0x prefix if present\n      const cleanKey = key.startsWith('0x') ? key.slice(2) : key\n      return PrivateKeyImpl.fromHex(cleanKey)\n    }\n    return PrivateKeyImpl.fromBytes(key)\n  }\n\n  /**\n   * Derives the public key from a private key.\n   *\n   * @remarks\n   * Uses Ed25519 elliptic curve cryptography to derive the public key from the\n   * given private key. The public key can be safely shared and is used for\n   * signature verification and address generation.\n   *\n   * @param privateKey - The private key to derive from\n   * @returns A promise that resolves to the corresponding PublicKey\n   *\n   * @throws Error if the private key is invalid\n   *\n   * @example\n   * ```typescript\n   * const provider = new DefaultCryptoProvider()\n   * const privateKey = provider.importPrivateKey('a1b2c3...')\n   * const publicKey = await provider.getPublicKey(privateKey)\n   *\n   * console.log('Public Key:', publicKey.toHex())\n   * console.log('Address:', publicKey.toAddress())\n   * ```\n   */\n  async getPublicKey(privateKey: PrivateKey): Promise<PublicKey> {\n    const pubKeyBytes = await getPublicKeyFromPrivate(privateKey.bytes)\n    return PublicKeyImpl.fromBytes(pubKeyBytes)\n  }\n\n  /**\n   * Signs a message using a private key.\n   *\n   * @remarks\n   * Creates a cryptographic signature that proves the message was signed by the\n   * holder of the private key. The signature can be verified by anyone with the\n   * corresponding public key.\n   *\n   * SECURITY WARNING: Never expose the private key used for signing.\n   *\n   * @param message - The message to sign as a Uint8Array\n   * @param privateKey - The private key used for signing\n   * @returns A promise that resolves to the Signature\n   *\n   * @throws Error if the private key is invalid or signing fails\n   *\n   * @example\n   * ```typescript\n   * const provider = new DefaultCryptoProvider()\n   * const privateKey = provider.importPrivateKey('a1b2c3...')\n   * const message = new TextEncoder().encode('Hello, Klever!')\n   *\n   * const signature = await provider.signMessage(message, privateKey)\n   * console.log('Signature (hex):', signature.toHex())\n   * console.log('Signature (base64):', signature.toBase64())\n   * ```\n   */\n  async signMessage(message: Uint8Array, privateKey: PrivateKey): Promise<Signature> {\n    const signatureBytes = await sign(message, privateKey.bytes)\n    return SignatureImpl.fromBytes(signatureBytes)\n  }\n\n  /**\n   * Verifies a signature against a message and public key.\n   *\n   * @remarks\n   * Verifies that a signature was created by the holder of the private key\n   * corresponding to the given public key. Returns true if valid, false otherwise.\n   *\n   * This function never throws on invalid signatures - it returns false instead,\n   * making it safe to use in validation logic.\n   *\n   * @param message - The original message that was signed\n   * @param signature - The signature to verify\n   * @param publicKey - The public key used for verification\n   * @returns A promise that resolves to true if the signature is valid, false otherwise\n   *\n   * @example\n   * ```typescript\n   * const provider = new DefaultCryptoProvider()\n   * const message = new TextEncoder().encode('Hello, Klever!')\n   * const signature = SignatureImpl.fromHex('...')\n   * const publicKey = PublicKeyImpl.fromHex('...')\n   *\n   * const isValid = await provider.verifySignature(message, signature, publicKey)\n   * console.log('Signature valid:', isValid)\n   * ```\n   */\n  async verifySignature(\n    message: Uint8Array,\n    signature: Signature,\n    publicKey: PublicKey,\n  ): Promise<boolean> {\n    return verify(message, signature.bytes, publicKey.bytes)\n  }\n\n  /**\n   * Converts a Klever address (bech32 format) to its raw bytes representation.\n   *\n   * @remarks\n   * Klever addresses use bech32 encoding (e.g., 'klv1...'). This method decodes\n   * the address to get the underlying public key bytes.\n   *\n   * @param address - The Klever address in bech32 format (e.g., 'klv1...')\n   * @returns A promise that resolves to the 32-byte public key as Uint8Array\n   *\n   * @throws Error if the address is invalid or malformed\n   *\n   * @example\n   * ```typescript\n   * const provider = new DefaultCryptoProvider()\n   * const bytes = await provider.addressToBytes('klv1abc123...')\n   * console.log('Address bytes:', bytes)\n   * ```\n   */\n  async addressToBytes(address: string): Promise<Uint8Array> {\n    const { data } = bech32Decode(address)\n    return data\n  }\n\n  /**\n   * Converts raw bytes to a Klever address (bech32 format).\n   *\n   * @remarks\n   * Encodes the public key bytes into a bech32-formatted Klever address (e.g., 'klv1...').\n   *\n   * @param bytes - The 32-byte public key as Uint8Array\n   * @returns A promise that resolves to the Klever address in bech32 format\n   *\n   * @throws Error if the bytes are invalid or not 32 bytes\n   *\n   * @example\n   * ```typescript\n   * const provider = new DefaultCryptoProvider()\n   * const publicKeyBytes = new Uint8Array(32) // Your public key bytes\n   * const address = await provider.bytesToAddress(publicKeyBytes)\n   * console.log('Address:', address)\n   * // Prints: klv1...\n   * ```\n   */\n  async bytesToAddress(bytes: Uint8Array): Promise<string> {\n    return bech32Encode(bytes)\n  }\n\n  /**\n   * Signs data using a private key hex string.\n   *\n   * @remarks\n   * Convenience method that accepts a private key as a hex string and returns\n   * the signature bytes directly. This is useful for quick signing operations\n   * without creating intermediate objects.\n   *\n   * SECURITY WARNING: Never expose the private key hex string in logs, network\n   * requests, or insecure storage.\n   *\n   * @param data - The data to sign as Uint8Array\n   * @param privateKeyHex - The private key as a hex string\n   * @returns A promise that resolves to the 64-byte signature as Uint8Array\n   *\n   * @throws Error if the private key is invalid or signing fails\n   *\n   * @example\n   * ```typescript\n   * const provider = new DefaultCryptoProvider()\n   * const data = new TextEncoder().encode('Hello, Klever!')\n   * const signatureBytes = await provider.sign(data, 'a1b2c3...')\n   * console.log('Signature bytes:', signatureBytes)\n   * ```\n   */\n  async sign(data: Uint8Array, privateKeyHex: string): Promise<Uint8Array> {\n    const privateKey = this.importPrivateKey(privateKeyHex)\n    const signature = await this.signMessage(data, privateKey)\n    return signature.bytes\n  }\n\n  /**\n   * Imports a private key from PEM format content.\n   *\n   * @remarks\n   * Loads a private key from PEM-formatted content. Supports both encrypted and\n   * unencrypted PEM files. For encrypted files, a password must be provided.\n   *\n   * The PEM file is verified to ensure the private key corresponds to the address\n   * claimed in the PEM header, preventing tampering or mistakes.\n   *\n   * SECURITY WARNINGS:\n   * - Use strong passwords for PEM encryption (minimum 12 characters, mix of letters, numbers, symbols)\n   * - Store PEM files securely with appropriate file permissions\n   * - Never transmit unencrypted PEM files over insecure channels\n   * - Consider using hardware wallets for production applications\n   *\n   * @param pemContent - The PEM file content as a string\n   * @param options - Loading options including password and key index\n   * @returns A promise that resolves to the imported PrivateKey\n   *\n   * @throws Error if the PEM is invalid, password is incorrect, or address verification fails\n   *\n   * @example\n   * ```typescript\n   * const provider = new DefaultCryptoProvider()\n   *\n   * // Load encrypted PEM\n   * const pemContent = '-----BEGIN PRIVATE KEY for klv1...-----\\n...'\n   * const privateKey = await provider.importPrivateKeyFromPem(pemContent, {\n   *   password: 'your-secure-password',\n   *   index: 0\n   * })\n   *\n   * // Load unencrypted PEM\n   * const privateKey2 = await provider.importPrivateKeyFromPem(pemContent)\n   * ```\n   */\n  async importPrivateKeyFromPem(pemContent: string, options?: LoadPemOptions): Promise<PrivateKey> {\n    const { privateKey } = await loadPrivateKeyFromPem(pemContent, options)\n    return PrivateKeyImpl.fromBytes(privateKey)\n  }\n\n  /**\n   * Imports a private key from a PEM file (Node.js only).\n   *\n   * @remarks\n   * Convenience method that reads a PEM file from the filesystem and imports the\n   * private key. This method is only available in Node.js environments.\n   *\n   * Supports both encrypted and unencrypted PEM files. For encrypted files,\n   * a password must be provided.\n   *\n   * SECURITY WARNINGS:\n   * - Store PEM files with restrictive permissions (e.g., 600 on Unix systems)\n   * - Use strong passwords for PEM encryption (minimum 12 characters, mix of letters, numbers, symbols)\n   * - Never commit PEM files to version control\n   * - Consider using hardware wallets for production applications\n   *\n   * @param filePath - The path to the PEM file\n   * @param options - Loading options including password and key index\n   * @returns A promise that resolves to the imported PrivateKey\n   *\n   * @throws Error if not in Node.js environment, file cannot be read, or PEM is invalid\n   *\n   * @example\n   * ```typescript\n   * const provider = new DefaultCryptoProvider()\n   *\n   * // Load encrypted PEM file\n   * const privateKey = await provider.importPrivateKeyFromPemFile(\n   *   './wallet.pem',\n   *   { password: 'your-secure-password' }\n   * )\n   *\n   * // Load unencrypted PEM file\n   * const privateKey2 = await provider.importPrivateKeyFromPemFile('./wallet.pem')\n   * ```\n   */\n  async importPrivateKeyFromPemFile(\n    filePath: string,\n    options?: LoadPemOptions,\n  ): Promise<PrivateKey> {\n    const { privateKey } = await loadPrivateKeyFromPemFile(filePath, options)\n    return PrivateKeyImpl.fromBytes(privateKey)\n  }\n}\n\n/**\n * Default singleton instance of the CryptoProvider.\n *\n * @remarks\n * This is a pre-instantiated CryptoProvider instance that can be used throughout\n * the application. It's recommended to use this singleton instance rather than\n * creating new instances unless you need custom behavior.\n *\n * @example\n * ```typescript\n * import { cryptoProvider } from '@klever/connect-crypto'\n *\n * // Use the default provider\n * const keyPair = await cryptoProvider.generateKeyPair()\n * ```\n */\nexport const cryptoProvider = new DefaultCryptoProvider()\n","import { hmac } from '@noble/hashes/hmac'\nimport { sha512 } from '@noble/hashes/sha512'\n\nconst ED25519_SEED_KEY = new Uint8Array([101, 100, 50, 53, 53, 49, 57, 32, 115, 101, 101, 100]) // \"ed25519 seed\"\nconst HARDENED_OFFSET = 0x80000000\n\nexport interface PathComponent {\n  index: number\n  hardened: boolean\n}\n\n/**\n * Parse a BIP44 derivation path into components\n * Example: \"m/44'/690'/0'/0'/0'\" -> [{index: 44, hardened: true}, ...]\n */\nexport function parsePath(path: string): PathComponent[] {\n  if (!path.startsWith('m/')) {\n    throw new Error('Path must start with \"m/\"')\n  }\n\n  const components: PathComponent[] = []\n  const parts = path.slice(2).split('/') // Remove 'm/'\n\n  for (const part of parts) {\n    if (!part) continue\n\n    const hardened = part.endsWith(\"'\")\n    const indexStr = hardened ? part.slice(0, -1) : part\n    const index = parseInt(indexStr, 10)\n\n    if (isNaN(index) || index < 0) {\n      throw new Error(`Invalid path component: ${part}`)\n    }\n\n    components.push({ index, hardened })\n  }\n\n  return components\n}\n\nexport function getMasterKeyFromSeed(seed: Uint8Array): { key: Uint8Array; chainCode: Uint8Array } {\n  // HMAC-SHA512(key=\"ed25519 seed\", data=seed)\n  const hash = hmac(sha512, ED25519_SEED_KEY, seed)\n\n  return {\n    key: hash.slice(0, 32), // First 32 bytes = master key\n    chainCode: hash.slice(32, 64), // Last 32 bytes = chain code\n  }\n}\n\n/**\nDerive a child key from parent key and chain code\n*\n@remarks\nImportant: Ed25519 SLIP-10 requires all path components to be hardened.\nNon-hardened components will derive keys but the results will NOT be compatible\nwith other SLIP-10 Ed25519 implementations. Always use paths like\nm/44'/690'/0'/0'/0' (all components ending with ').\n@param parentKey - Parent private key (32 bytes)\n@param chainCode - Parent chain code (32 bytes)\n@param component - Path component with index and hardened flag\n@returns Derived child key and chain code\n*/\n\nexport function deriveChildKey(\n  parentKey: Uint8Array,\n  chainCode: Uint8Array,\n  component: PathComponent,\n): { key: Uint8Array; chainCode: Uint8Array } {\n  const data = new Uint8Array(1 + 32 + 4)\n\n  // 0x00 prefix\n  data[0] = 0\n\n  // Parent key (32 bytes)\n  data.set(parentKey, 1)\n\n  // Index (4 bytes, big-endian)\n  let index = component.index\n  if (component.hardened) {\n    index |= HARDENED_OFFSET\n  }\n  const view = new DataView(data.buffer)\n  view.setUint32(33, index, false) // false = big-endian\n\n  // HMAC-SHA512(key=chainCode, data=data)\n  const hash = hmac(sha512, chainCode, data)\n\n  return {\n    key: hash.slice(0, 32),\n    chainCode: hash.slice(32, 64),\n  }\n}\n\n/**\n * Derive a private key from seed following a derivation path\n *\n * @param seed - The master seed (from mnemonic)\n * @param path - BIP44 path like \"m/44'/690'/0'/0'/0'\"\n * @returns 32-byte Ed25519 private key\n *\n * @example\n * ```typescript\n * const seed = mnemonicToSeedSync(\"your mnemonic here\", \"\")\n * const privateKey = deriveEd25519PrivateKey(seed, \"m/44'/690'/0'/0'/0'\")\n * ```\n */\nexport function deriveEd25519PrivateKey(seed: Uint8Array, path: string): Uint8Array {\n  // Parse path\n  const components = parsePath(path)\n\n  // Get master key from seed\n  let { key, chainCode } = getMasterKeyFromSeed(seed)\n\n  // Derive through each path component\n  for (const component of components) {\n    const derived = deriveChildKey(key, chainCode, component)\n    key = derived.key\n    chainCode = derived.chainCode\n  }\n\n  return key\n}\n","import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'\nimport { wordlist } from '@scure/bip39/wordlists/english'\nimport { PrivateKeyImpl } from './keys'\nimport { deriveEd25519PrivateKey } from './slip10-ed25519'\nimport type { PrivateKey } from './types'\n\n// Default BIP44 derivation path for Klever\nexport const DEFAULT_DERIVATION_PATH = \"m/44'/690'/0'/0'/0'\"\n\n// Klever's registered coin type in BIP44\nexport const KLEVER_COIN_TYPE = 690\n\n// Valid mnemonic strengths in bits (12-24 words)\nexport type MnemonicStrength = 128 | 160 | 192 | 224 | 256\n\nexport interface GenerateMnemonicOptions {\n  strength?: MnemonicStrength\n}\n\nexport interface MnemonicToKeyOptions {\n  path?: string\n  passphrase?: string\n}\n\n/**\n * Generates a new BIP39 mnemonic phrase with specified strength.\n *\n * @param options - Generation options including strength\n * @returns A space-separated mnemonic phrase\n *\n * @throws Error if strength is not one of the valid values (128, 160, 192, 224, 256)\n *\n * @example\n * ```typescript\n * // Generate 12-word mnemonic (default)\n * const mnemonic = generateMnemonicPhrase()\n *\n * // Generate 24-word mnemonic\n * const strongMnemonic = generateMnemonicPhrase({ strength: 256 })\n * ```\n */\nexport function generateMnemonicPhrase(options: GenerateMnemonicOptions = {}): string {\n  const { strength = 128 } = options\n\n  if (![128, 160, 192, 224, 256].includes(strength)) {\n    throw new Error('Invalid strength. Must be 128, 160, 192, 224, or 256')\n  }\n\n  return generateMnemonic(wordlist, strength)\n}\n\n/**\n * Validates a BIP39 mnemonic phrase.\n *\n * @param mnemonic - The mnemonic phrase to validate\n * @returns True if the mnemonic is valid, false otherwise\n *\n * @example\n * ```typescript\n * const isValid = isValidMnemonic('abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about')\n * console.log(isValid) // true\n * ```\n */\nexport function isValidMnemonic(mnemonic: string): boolean {\n  return validateMnemonic(mnemonic, wordlist)\n}\n\n/**\n * Converts a mnemonic phrase to a private key using SLIP-0010 Ed25519 derivation.\n *\n *\n * @param mnemonic - The BIP39 mnemonic phrase\n * @param options - Options including derivation path and passphrase\n * @returns The derived private key\n *\n * @throws Error if the mnemonic phrase is invalid\n * @throws Error if the derivation fails or produces an invalid key\n *\n * @example\n * ```typescript\n * // Derive with default path\n * const key = mnemonicToPrivateKey('your mnemonic phrase here')\n *\n * // Derive with custom path and passphrase\n * const key2 = mnemonicToPrivateKey('your mnemonic phrase here', {\n *   path: \"m/44'/690'/0'/0'/1'\",\n *   passphrase: 'optional-passphrase'\n * })\n * ```\n */\nexport function mnemonicToPrivateKey(\n  mnemonic: string,\n  options: MnemonicToKeyOptions = {},\n): PrivateKey {\n  const { path = DEFAULT_DERIVATION_PATH, passphrase = '' } = options\n\n  if (!isValidMnemonic(mnemonic)) {\n    throw new Error('Invalid mnemonic phrase')\n  }\n\n  // Convert mnemonic to seed\n  const seed = mnemonicToSeedSync(mnemonic, passphrase)\n\n  const privateKeyBytes = deriveEd25519PrivateKey(seed, path)\n\n  // Ensure key is 32 bytes (256 bits)\n  if (privateKeyBytes.length !== 32) {\n    throw new Error(`Invalid derived key length: ${privateKeyBytes.length}`)\n  }\n\n  return PrivateKeyImpl.fromBytes(privateKeyBytes)\n}\n\n/**\n * Derives multiple sequential private keys from a mnemonic phrase.\n *\n * @remarks\n * This function takes the base derivation path and increments the last index\n * to generate multiple keys sequentially. For example, if the path is\n * \"m/44'/690'/0'/0'/0'\", it will generate keys at indices 0', 1', 2', etc.\n *\n * @param mnemonic - The BIP39 mnemonic phrase\n * @param count - Number of keys to derive (must be at least 1)\n * @param options - Options including derivation path and passphrase\n * @returns Array of derived private keys\n *\n * @throws Error if count is less than 1\n * @throws Error if the mnemonic phrase is invalid\n *\n * @example\n * ```typescript\n * // Derive 5 sequential keys starting from default path\n * const keys = deriveMultipleKeys('your mnemonic here', 5)\n * // Generates keys at: m/44'/690'/0'/0'/0', m/44'/690'/0'/0'/1', ..., m/44'/690'/0'/0'/4'\n *\n * // Derive with custom starting path\n * const keys2 = deriveMultipleKeys('your mnemonic here', 3, {\n *   path: \"m/44'/690'/0'/0'/10'\"\n * })\n * // Generates keys at: m/44'/690'/0'/0'/10', m/44'/690'/0'/0'/11', m/44'/690'/0'/0'/12'\n * ```\n */\nexport function deriveMultipleKeys(\n  mnemonic: string,\n  count: number,\n  options: MnemonicToKeyOptions = {},\n): PrivateKey[] {\n  if (count < 1) {\n    throw new Error('Count must be at least 1')\n  }\n\n  const { path = DEFAULT_DERIVATION_PATH, passphrase } = options\n\n  // Extract base path and starting index from derivation path\n  const pathParts = path.split('/')\n  const lastPart = pathParts[pathParts.length - 1] || '0'\n  const isHardened = lastPart.endsWith(\"'\")\n  const basePath = pathParts.slice(0, -1).join('/')\n  const startIndex = parseInt(pathParts[pathParts.length - 1] || '0', 10)\n\n  const keys: PrivateKey[] = []\n\n  // Generate keys by incrementing the last index\n  for (let i = 0; i < count; i++) {\n    const indexSuffix = isHardened ? \"'\" : ''\n    const derivationPath = `${basePath}/${startIndex + i}${indexSuffix}`\n    const key =\n      passphrase !== undefined\n        ? mnemonicToPrivateKey(mnemonic, { path: derivationPath, passphrase })\n        : mnemonicToPrivateKey(mnemonic, { path: derivationPath })\n    keys.push(key)\n  }\n\n  return keys\n}\n\n/**\n * Builds a BIP44 derivation path for Klever accounts.\n *\n * @remarks\n * Constructs a derivation path following the BIP44 standard:\n * m/44'/coin_type'/account'/change'/index'\n *\n * Where:\n * - 44' is the BIP44 purpose (hardened)\n * - coin_type is Klever's registered coin type (690, hardened)\n * - account' is the account index (hardened)\n * - change' is 0' for external (receiving) or 1' for internal (change) addresses (hardened)\n * - index' is the address index (hardened)\n *\n * @param account - Account index (default: 0, must be non-negative integer)\n * @param change - Chain type: 0 for external, 1 for internal (default: 0)\n * @param index - Address index (default: 0, must be non-negative integer)\n * @returns The formatted BIP44 derivation path\n *\n * @throws Error if account is negative or not an integer\n * @throws Error if change is not 0 or 1\n * @throws Error if index is negative or not an integer\n *\n * @example\n * ```typescript\n * // Build default path\n * const path1 = buildDerivationPath()\n * // Returns: \"m/44'/690'/0'/0'/0'\"\n *\n * // Build path for second account, first address\n * const path2 = buildDerivationPath(1, 0, 0)\n * // Returns: \"m/44'/690'/1'/0'/0'\"\n *\n * // Build path for change address\n * const path3 = buildDerivationPath(0, 1, 5)\n * // Returns: \"m/44'/690'/0'/1'/5'\"\n * ```\n */\nexport function buildDerivationPath(\n  account: number = 0,\n  change: number = 0,\n  index: number = 0,\n): string {\n  if (account < 0 || !Number.isInteger(account)) {\n    throw new Error('Account must be a non-negative integer')\n  }\n  if (change < 0 || change > 1 || !Number.isInteger(change)) {\n    throw new Error('Change must be 0 (external) or 1 (internal)')\n  }\n  if (index < 0 || !Number.isInteger(index)) {\n    throw new Error('Index must be a non-negative integer')\n  }\n\n  return `m/44'/${KLEVER_COIN_TYPE}'/${account}'/${change}'/${index}'`\n}\n","import { hexDecode, hexEncode } from '@klever/connect-encoding'\nimport { scrypt } from '@noble/hashes/scrypt'\nimport { randomBytes } from '@noble/hashes/utils'\nimport { PrivateKeyImpl } from './keys'\nimport type { PrivateKey } from './types'\n\nexport interface Keystore {\n  version: 1\n  id: string\n  address: string\n  crypto: {\n    ciphertext: string\n    cipherparams: {\n      iv: string\n      tag: string\n    }\n    cipher: 'aes-256-gcm'\n    kdf: 'scrypt'\n    kdfparams: {\n      dklen: number\n      salt: string\n      n: number\n      r: number\n      p: number\n    }\n  }\n}\n\nexport interface EncryptOptions {\n  scryptN?: number\n  scryptR?: number\n  scryptP?: number\n}\n\nexport const DEFAULT_SCRYPT_PARAMS = {\n  n: 262144,\n  r: 8,\n  p: 1,\n  dklen: 32,\n}\n\n// Generates a RFC4122 version 4 UUID\nfunction generateUUID(): string {\n  const bytes = randomBytes(16)\n  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n  bytes[6] = (bytes[6]! & 0x0f) | 0x40\n  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n  bytes[8] = (bytes[8]! & 0x3f) | 0x80\n\n  const hex = hexEncode(bytes)\n  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`\n}\n\n/**\n * Encrypts data using AES-256-GCM\n *\n * @remarks\n * AES-256-GCM provides both confidentiality and authenticity in a single operation.\n * The authentication tag is automatically generated and returned separately.\n *\n * **IV Requirements (Critical for Security):**\n * - Must be 96 bits (12 bytes) for optimal GCM performance\n * - Must be UNIQUE for every encryption with the same key\n * - Must be generated using a cryptographically secure random number generator\n * - Does NOT need to be secret (can be transmitted in the clear)\n * - NEVER reuse an IV with the same key (catastrophic security failure)\n *\n * @param data - Data to encrypt\n * @param key - 256-bit (32 byte) encryption key\n * @param iv - Initialization vector (must be 12 bytes, unique per encryption)\n * @returns Object containing ciphertext and authentication tag\n */\nasync function aes256GcmEncrypt(\n  data: Uint8Array,\n  key: Uint8Array,\n  iv: Uint8Array,\n): Promise<{ ciphertext: Uint8Array; tag: Uint8Array }> {\n  const cryptoKey = await crypto.subtle.importKey(\n    'raw',\n    key as BufferSource,\n    { name: 'AES-GCM' },\n    false,\n    ['encrypt'],\n  )\n\n  const encrypted = await crypto.subtle.encrypt(\n    {\n      name: 'AES-GCM',\n      iv: iv as BufferSource,\n      tagLength: 128,\n    },\n    cryptoKey,\n    data as BufferSource,\n  )\n  const encryptedArray = new Uint8Array(encrypted)\n  const ciphertext = encryptedArray.slice(0, -16) // Ciphertext (all except last 16 bytes)\n  const tag = encryptedArray.slice(-16) // Authentication tag (last 16 bytes)\n\n  return { ciphertext, tag }\n}\n\n/**\n * Decrypts data using AES-256-GCM and verifies authenticity\n *\n * @remarks\n * AES-256-GCM automatically verifies the authentication tag during decryption.\n * If the tag is invalid (wrong password or tampered data), decryption will fail.\n *\n * @param ciphertext - Encrypted data\n * @param key - 256-bit (32 byte) decryption key\n * @param iv - Initialization vector used during encryption\n * @param tag - Authentication tag for verification\n * @returns Decrypted plaintext data\n * @throws Error if authentication fails (wrong password or tampered data)\n */\nasync function aes256GcmDecrypt(\n  ciphertext: Uint8Array,\n  key: Uint8Array,\n  iv: Uint8Array,\n  tag: Uint8Array,\n): Promise<Uint8Array> {\n  const cryptoKey = await crypto.subtle.importKey(\n    'raw',\n    key as BufferSource,\n    { name: 'AES-GCM' },\n    false,\n    ['decrypt'],\n  )\n\n  const combined = new Uint8Array(ciphertext.length + tag.length)\n  combined.set(ciphertext, 0)\n  combined.set(tag, ciphertext.length) // Append 16-byte tag at the end\n\n  const decrypted = await crypto.subtle.decrypt(\n    {\n      name: 'AES-GCM',\n      iv: iv as BufferSource,\n      tagLength: 128, // Must match the tagLength used during encryption\n    },\n    cryptoKey,\n    combined,\n  )\n\n  return new Uint8Array(decrypted)\n}\n\n/**\n * Encrypts a private key into a Klever Keystore V1 format.\n *\n * @remarks\n * This function uses the scrypt key derivation function (KDF) with AES-256-GCM authenticated\n * encryption to securely encrypt a private key with a password.\n *\n * Security features:\n * - Scrypt KDF with configurable parameters (default N=262144 for strong security)\n * - AES-256-GCM authenticated encryption\n * - 256-bit encryption key (stronger than AES-128)\n * - Built-in authentication tag for integrity verification\n * - Cryptographically random 12-byte IV (unique per encryption, per AES-GCM spec)\n * - Random 32-byte salt for scrypt KDF\n *\n * @param privateKey - The private key to encrypt\n * @param password - Password to protect the keystore (minimum 8 characters)\n * @param address - The wallet address associated with this key\n * @param options - Optional scrypt parameters (N, r, p) for custom security levels\n * @returns A promise that resolves to the encrypted keystore object\n *\n * @throws Error if password is empty or less than 8 characters\n * @throws Error if scryptN is not a power of 2\n * @throws Error if scryptR or scryptP are not positive numbers\n *\n * @example\n * ```typescript\n * import { generateKeyPair } from '@klever/connect-crypto'\n *\n * // Generate a key pair\n * const { privateKey, publicKey } = await generateKeyPair()\n * const address = 'klv1...'\n *\n * // Encrypt with default parameters (strong security)\n * const keystore = await encryptToKeystore(privateKey, 'my-secure-password', address)\n *\n * // Encrypt with custom parameters (faster, less secure - useful for testing)\n * const testKeystore = await encryptToKeystore(privateKey, 'password', address, {\n *   scryptN: 4096,  // Lower N = faster but less secure\n *   scryptR: 8,\n *   scryptP: 1\n * })\n *\n * // Save keystore to file\n * const keystoreJson = JSON.stringify(keystore, null, 2)\n * ```\n */\nexport async function encryptToKeystore(\n  privateKey: PrivateKey | Uint8Array,\n  password: string,\n  address: string,\n  options: EncryptOptions = {},\n): Promise<Keystore> {\n  // Password validation\n  if (!password || password.length === 0) {\n    throw new Error('Password cannot be empty')\n  }\n  if (password.length < 8) {\n    throw new Error('Password must be at least 8 characters')\n  }\n  const {\n    scryptN = DEFAULT_SCRYPT_PARAMS.n,\n    scryptR = DEFAULT_SCRYPT_PARAMS.r,\n    scryptP = DEFAULT_SCRYPT_PARAMS.p,\n  } = options\n\n  if (scryptN <= 0 || (scryptN & (scryptN - 1)) !== 0) {\n    throw new Error('scryptN must be a power of 2')\n  }\n  if (scryptR <= 0 || scryptP <= 0) {\n    throw new Error('scryptR and scryptP must be positive')\n  }\n\n  // Generate random salt and IV\n  const salt = randomBytes(32)\n  const iv = randomBytes(12) // AES-GCM spec recommends 96-bit (12-byte) IV\n\n  // Derive 32-byte key from password using scrypt\n  const derivedKey = scrypt(password, salt, {\n    N: scryptN,\n    r: scryptR,\n    p: scryptP,\n    dkLen: DEFAULT_SCRYPT_PARAMS.dklen,\n  })\n\n  // Use all 32 bytes for encryption\n  const encryptionKey = derivedKey\n\n  // Get private key bytes\n  const privateKeyBytes = privateKey instanceof Uint8Array ? privateKey : privateKey.bytes\n\n  // Encrypt private key\n  const { ciphertext, tag } = await aes256GcmEncrypt(privateKeyBytes, encryptionKey, iv)\n\n  const keystore: Keystore = {\n    version: 1,\n    id: generateUUID(),\n    address: address.replace(/^klv1?/, ''),\n    crypto: {\n      ciphertext: hexEncode(ciphertext),\n      cipherparams: {\n        iv: hexEncode(iv),\n        tag: hexEncode(tag),\n      },\n      cipher: 'aes-256-gcm',\n      kdf: 'scrypt',\n      kdfparams: {\n        dklen: DEFAULT_SCRYPT_PARAMS.dklen,\n        salt: hexEncode(salt),\n        n: scryptN,\n        r: scryptR,\n        p: scryptP,\n      },\n    },\n  }\n\n  return keystore\n}\n\n/**\n * Decrypts a Klever Keystore V1 to retrieve the private key.\n *\n * @remarks\n * This function decrypts a keystore encrypted with Klever's V1 format using AES-256-GCM\n * authenticated encryption. The authentication tag is automatically verified during\n * decryption, ensuring both the password is correct and the keystore hasn't been tampered with.\n *\n * Supported formats:\n * - Version 1 keystores only\n * - AES-256-GCM cipher\n * - Scrypt KDF\n *\n * @param keystore - The keystore object or JSON string to decrypt\n * @param password - The password used to encrypt the keystore\n * @returns A promise that resolves to the decrypted private key\n *\n * @throws Error if keystore version is not 1\n * @throws Error if cipher is not 'aes-256-gcm'\n * @throws Error if KDF is not 'scrypt'\n * @throws Error if password is incorrect (GCM authentication failed)\n * @throws Error if keystore is corrupted or tampered with\n * @throws Error if decrypted private key length is not 32 bytes\n *\n * @example\n * ```typescript\n * import { cryptoProvider } from '@klever/connect-crypto'\n *\n * // Decrypt from keystore object\n * const privateKey = await decryptKeystore(keystore, 'my-secure-password')\n *\n * // Decrypt from JSON string\n * const keystoreJson = '{\"version\":1,\"id\":\"...\",\"crypto\":{...}}'\n * const privateKey2 = await decryptKeystore(keystoreJson, 'password')\n *\n * // Use the decrypted private key\n * console.log('Private key hex:', privateKey.toHex())\n * const publicKey = await cryptoProvider.getPublicKey(privateKey)\n * const address = publicKey.toAddress()\n * ```\n */\nexport async function decryptKeystore(\n  keystore: Keystore | string,\n  password: string,\n): Promise<PrivateKey> {\n  const ks: Keystore = typeof keystore === 'string' ? JSON.parse(keystore) : keystore\n\n  // Validate keystore format\n  if (ks.version !== 1) {\n    throw new Error('Unsupported keystore version: ' + String(ks.version))\n  }\n\n  if (ks.crypto.cipher !== 'aes-256-gcm') {\n    throw new Error('Unsupported cipher: ' + String(ks.crypto.cipher))\n  }\n\n  if (ks.crypto.kdf !== 'scrypt') {\n    throw new Error('Unsupported KDF: ' + String(ks.crypto.kdf))\n  }\n\n  const { ciphertext, cipherparams, kdfparams } = ks.crypto\n\n  // Decode hex strings\n  const ciphertextBytes = hexDecode(ciphertext)\n  const iv = hexDecode(cipherparams.iv)\n  const tag = hexDecode(cipherparams.tag)\n  const salt = hexDecode(kdfparams.salt)\n\n  // Derive key from password\n  const derivedKey = scrypt(password, salt, {\n    N: kdfparams.n,\n    r: kdfparams.r,\n    p: kdfparams.p,\n    dkLen: kdfparams.dklen,\n  })\n\n  // Decrypt private key with AES-256-GCM\n  // GCM automatically verifies the authentication tag, throwing an error if\n  // the password is wrong or the keystore has been tampered with\n  const encryptionKey = derivedKey\n  try {\n    const privateKeyBytes = await aes256GcmDecrypt(ciphertextBytes, encryptionKey, iv, tag)\n\n    if (privateKeyBytes.length !== 32) {\n      throw new Error(`Invalid private key length: ${privateKeyBytes.length}`)\n    }\n\n    return PrivateKeyImpl.fromBytes(privateKeyBytes)\n  } catch {\n    throw new Error('Invalid password or corrupted keystore (authentication failed)')\n  }\n}\n\n/**\n * Checks if a password is correct for a keystore.\n *\n * @remarks\n * This function verifies if a password is correct by attempting to decrypt the keystore.\n * With AES-256-GCM, authentication is performed during decryption, so we must actually\n * decrypt to verify the password..\n *\n * @param keystore - The keystore object or JSON string to check\n * @param password - The password to verify\n * @returns A promise that resolves to true if password is correct, false otherwise\n *\n * @example\n * ```typescript\n * // Verify password before using the private key\n * const isValid = await isPasswordCorrect(keystore, 'my-password')\n * if (isValid) {\n *   const privateKey = await decryptKeystore(keystore, 'my-password')\n *   console.log('Decryption successful!')\n * } else {\n *   console.error('Invalid password')\n * }\n *\n * // Quick password validation\n * if (!await isPasswordCorrect(keystore, userInput)) {\n *   throw new Error('Incorrect password')\n * }\n * ```\n */\nexport async function isPasswordCorrect(\n  keystore: Keystore | string,\n  password: string,\n): Promise<boolean> {\n  try {\n    await decryptKeystore(keystore, password)\n    return true\n  } catch {\n    return false\n  }\n}\n"]}