interface KeyPair { privateKey: PrivateKey; publicKey: PublicKey; } interface PrivateKey { bytes: Uint8Array; hex: string; toHex(): string; } interface PublicKey { bytes: Uint8Array; hex: string; toHex(): string; toAddress(): string; } interface Signature { bytes: Uint8Array; hex: string; toHex(): string; toBase64(): string; } interface SignableMessage { toBytes(): Uint8Array; } interface LoadPemOptions { password?: string; index?: number; } interface CryptoProvider { generateKeyPair(): Promise; importPrivateKey(key: string | Uint8Array): PrivateKey; getPublicKey(privateKey: PrivateKey): Promise; signMessage(message: Uint8Array, privateKey: PrivateKey): Promise; verifySignature(message: Uint8Array, signature: Signature, publicKey: PublicKey): Promise; addressToBytes(address: string): Promise; bytesToAddress(bytes: Uint8Array): Promise; sign(data: Uint8Array, privateKeyHex: string): Promise; importPrivateKeyFromPem?(pemContent: string, options?: LoadPemOptions): Promise; importPrivateKeyFromPemFile?(filePath: string, options?: LoadPemOptions): Promise; } /** * Implementation of a private key using Ed25519 cryptography. * * @remarks * This class represents a 32-byte Ed25519 private key used for signing transactions * and messages on the Klever blockchain. * * SECURITY WARNING: Never expose private keys in logs, network requests, or insecure storage. * Private keys should be stored securely (encrypted or in hardware wallets) and never * transmitted over insecure channels. * * @example * ```typescript * // Create from hex string * const privateKey = PrivateKeyImpl.fromHex('a1b2c3...') * * // Create from bytes * const privateKey = PrivateKeyImpl.fromBytes(new Uint8Array(32)) * * // Convert to hex * const hex = privateKey.toHex() * ``` */ declare class PrivateKeyImpl implements PrivateKey { readonly bytes: Uint8Array; constructor(bytes: Uint8Array); get hex(): string; toHex(): string; static fromHex(hex: string): PrivateKeyImpl; static fromBytes(bytes: Uint8Array): PrivateKeyImpl; } /** * Implementation of a public key using Ed25519 cryptography. * * @remarks * This class represents a 32-byte Ed25519 public key derived from a private key. * Public keys are used to verify signatures and can be safely shared. * They can also be converted to Klever blockchain addresses. * * @example * ```typescript * // Create from hex string * const publicKey = PublicKeyImpl.fromHex('a1b2c3...') * * // Create from bytes * const publicKey = PublicKeyImpl.fromBytes(new Uint8Array(32)) * * // Convert to Klever address (bech32 format) * const address = publicKey.toAddress() * // Returns: 'klv1...' * * // Convert to hex * const hex = publicKey.toHex() * ``` */ declare class PublicKeyImpl implements PublicKey { readonly bytes: Uint8Array; constructor(bytes: Uint8Array); get hex(): string; toHex(): string; toAddress(): string; static fromHex(hex: string): PublicKeyImpl; static fromBytes(bytes: Uint8Array): PublicKeyImpl; } /** * Generates a new Ed25519 key pair asynchronously using cryptographically secure random bytes. * * @remarks * This function uses the noble-ed25519 library to generate a secure random private key * and derives the corresponding public key. The asynchronous version is recommended * for better performance in environments that support it. * * SECURITY WARNING: The generated private key must be stored securely. Never expose * it in logs, network requests, or insecure storage. Consider using hardware wallets * or encrypted storage for production applications. * * @returns A promise that resolves to a KeyPair object containing both private and public keys * * @example * ```typescript * // Generate a new key pair * const keyPair = await generateKeyPair() * * // Access the keys * const privateKeyHex = keyPair.privateKey.toHex() * const publicKeyHex = keyPair.publicKey.toHex() * const address = keyPair.publicKey.toAddress() * * console.log('Address:', address) * // Prints: klv1... * ``` */ declare function generateKeyPair(): Promise; /** * Generates a new Ed25519 key pair synchronously using cryptographically secure random bytes. * * @remarks * This function uses the noble-ed25519 library to generate a secure random private key * and derives the corresponding public key. The synchronous version is provided for * environments that don't support async operations, but the async version is generally * preferred for better performance. * * SECURITY WARNING: The generated private key must be stored securely. Never expose * it in logs, network requests, or insecure storage. Consider using hardware wallets * or encrypted storage for production applications. * * @returns A KeyPair object containing both private and public keys * * @example * ```typescript * // Generate a new key pair synchronously * const keyPair = generateKeyPairSync() * * // Access the keys * const privateKeyHex = keyPair.privateKey.toHex() * const publicKeyHex = keyPair.publicKey.toHex() * const address = keyPair.publicKey.toAddress() * * console.log('Address:', address) * // Prints: klv1... * ``` */ declare function generateKeyPairSync(): KeyPair; /** * Derives the public key from a private key asynchronously. * * @remarks * This function uses Ed25519 elliptic curve cryptography to derive the public key * from the given private key. The public key can be safely shared and is used for * signature verification and address generation. * * @param privateKey - The 32-byte private key as a Uint8Array * @returns A promise that resolves to the 32-byte public key as a Uint8Array * * @throws Error if the private key is invalid or not 32 bytes * * @example * ```typescript * const privateKeyBytes = new Uint8Array(32) // Your private key bytes * const publicKeyBytes = await getPublicKeyFromPrivate(privateKeyBytes) * * // Convert to PublicKeyImpl for additional methods * const publicKey = PublicKeyImpl.fromBytes(publicKeyBytes) * const address = publicKey.toAddress() * ``` */ declare function getPublicKeyFromPrivate(privateKey: Uint8Array): Promise; /** * Derives the public key from a private key synchronously. * * @remarks * This function uses Ed25519 elliptic curve cryptography to derive the public key * from the given private key. The synchronous version is provided for environments * that don't support async operations, but the async version is generally preferred. * * @param privateKey - The 32-byte private key as a Uint8Array * @returns The 32-byte public key as a Uint8Array * * @throws Error if the private key is invalid or not 32 bytes * * @example * ```typescript * const privateKeyBytes = new Uint8Array(32) // Your private key bytes * const publicKeyBytes = getPublicKeyFromPrivateSync(privateKeyBytes) * * // Convert to PublicKeyImpl for additional methods * const publicKey = PublicKeyImpl.fromBytes(publicKeyBytes) * const address = publicKey.toAddress() * ``` */ declare function getPublicKeyFromPrivateSync(privateKey: Uint8Array): Uint8Array; /** * Implementation of a cryptographic signature using Ed25519. * * @remarks * This class represents a 64-byte Ed25519 signature generated by signing a message * with a private key. Signatures can be verified using the corresponding public key * to ensure message authenticity and integrity. * * Signatures can be encoded in multiple formats: * - Hex (hexadecimal string) * - Base64 (base64 string) * - Raw bytes (Uint8Array) * * @example * ```typescript * // Create from hex string * const signature = SignatureImpl.fromHex('a1b2c3...') * * // Create from base64 string * const signature = SignatureImpl.fromBase64('YWJjZGVm...') * * // Create from bytes * const signature = SignatureImpl.fromBytes(new Uint8Array(64)) * * // Convert to different formats * const hex = signature.toHex() * const base64 = signature.toBase64() * const bytes = signature.bytes * ``` */ declare class SignatureImpl implements Signature { readonly bytes: Uint8Array; constructor(bytes: Uint8Array); get hex(): string; toHex(): string; toBase64(): string; static fromHex(hex: string): SignatureImpl; static fromBase64(base64: string): SignatureImpl; static fromBytes(bytes: Uint8Array): SignatureImpl; } /** * Signs a message asynchronously using Ed25519 cryptography. * * @remarks * This function creates a cryptographic signature that proves the message was signed * by the holder of the private key. The signature can be verified by anyone with the * corresponding public key to ensure message authenticity and integrity. * * SECURITY WARNING: Never expose the private key used for signing. Ensure the private * key is stored securely and never transmitted over insecure channels. * * @param message - The message to sign as a Uint8Array (often a transaction hash) * @param privateKey - The 32-byte private key used for signing * @returns A promise that resolves to a 64-byte signature as a Uint8Array * * @throws Error if the private key is invalid or signing fails * * @example * ```typescript * const message = new TextEncoder().encode('Hello, Klever!') * const privateKey = new Uint8Array(32) // Your private key bytes * * const signatureBytes = await signMessage(message, privateKey) * * // Convert to SignatureImpl for additional methods * const signature = SignatureImpl.fromBytes(signatureBytes) * console.log('Signature (hex):', signature.toHex()) * console.log('Signature (base64):', signature.toBase64()) * ``` */ declare function signMessage(message: Uint8Array, privateKey: Uint8Array): Promise; /** * Signs a message synchronously using Ed25519 cryptography. * * @remarks * This function creates a cryptographic signature that proves the message was signed * by the holder of the private key. The signature can be verified by anyone with the * corresponding public key to ensure message authenticity and integrity. * * The synchronous version is provided for environments that don't support async * operations, but the async version is generally preferred for better performance. * * SECURITY WARNING: Never expose the private key used for signing. Ensure the private * key is stored securely and never transmitted over insecure channels. * * @param message - The message to sign as a Uint8Array (often a transaction hash) * @param privateKey - The 32-byte private key used for signing * @returns A 64-byte signature as a Uint8Array * * @throws Error if the private key is invalid or signing fails * * @example * ```typescript * const message = new TextEncoder().encode('Hello, Klever!') * const privateKey = new Uint8Array(32) // Your private key bytes * * const signatureBytes = signMessageSync(message, privateKey) * * // Convert to SignatureImpl for additional methods * const signature = SignatureImpl.fromBytes(signatureBytes) * console.log('Signature (hex):', signature.toHex()) * ``` */ declare function signMessageSync(message: Uint8Array, privateKey: Uint8Array): Uint8Array; /** * Verifies a signature asynchronously using Ed25519 cryptography. * * @remarks * This function verifies that a signature was created by the holder of the private key * corresponding to the given public key. It ensures message authenticity and integrity. * * Returns true if the signature is valid, false otherwise. This function never throws * on invalid signatures - it returns false instead, making it safe to use in validation logic. * * @param message - The original message that was signed * @param signature - The 64-byte signature to verify * @param publicKey - The 32-byte public key used for verification * @returns A promise that resolves to true if the signature is valid, false otherwise * * @example * ```typescript * const message = new TextEncoder().encode('Hello, Klever!') * const signatureBytes = new Uint8Array(64) // Signature from signMessage * const publicKeyBytes = new Uint8Array(32) // Public key * * const isValid = await verifySignature(message, signatureBytes, publicKeyBytes) * * if (isValid) { * console.log('Signature is valid!') * } else { * console.log('Invalid signature') * } * ``` */ declare function verifySignature(message: Uint8Array, signature: Uint8Array, publicKey: Uint8Array): Promise; /** * Verifies a signature synchronously using Ed25519 cryptography. * * @remarks * This function verifies that a signature was created by the holder of the private key * corresponding to the given public key. It ensures message authenticity and integrity. * * The synchronous version is provided for environments that don't support async * operations, but the async version is generally preferred for better performance. * * Returns true if the signature is valid, false otherwise. This function never throws * on invalid signatures - it returns false instead, making it safe to use in validation logic. * * @param message - The original message that was signed * @param signature - The 64-byte signature to verify * @param publicKey - The 32-byte public key used for verification * @returns True if the signature is valid, false otherwise * * @example * ```typescript * const message = new TextEncoder().encode('Hello, Klever!') * const signatureBytes = new Uint8Array(64) // Signature from signMessageSync * const publicKeyBytes = new Uint8Array(32) // Public key * * const isValid = verifySignatureSync(message, signatureBytes, publicKeyBytes) * * if (isValid) { * console.log('Signature is valid!') * } else { * console.log('Invalid signature') * } * ``` */ declare function verifySignatureSync(message: Uint8Array, signature: Uint8Array, publicKey: Uint8Array): boolean; /** * Prepares a plaintext message for KLV chain signature verification. * * @remarks * The Klever browser extension (kos-rs `KLV::prepare_message`) applies this * protocol before Ed25519-signing any message: * * 1. Prepend the 23-byte prefix `"\x17Klever Signed Message:\n"` * 2. Append the UTF-8 byte length of the message as an ASCII decimal string * 3. Append the UTF-8-encoded message bytes * 4. Return the keccak256 digest of the concatenated data * * Use the returned 32-byte hash as the `message` argument to `verifySignature` * whenever the signature was produced by `window.kleverWeb.signMessage` or * `BrowserWallet.signMessage` (extension mode). * * @param message - The original plaintext message string * @returns A 32-byte keccak256 digest ready for Ed25519 signature verification * * @example * ```typescript * const messageHash = prepareKlvMessage('Submit validation for contract klv1...') * const isValid = await verifySignature(messageHash, signatureBytes, publicKeyBytes) * ``` */ declare function prepareKlvMessage(message: string): Uint8Array; /** * Verifies a message signature produced by the Klever browser extension. * * @remarks * Combines `prepareKlvMessage` and `verifySignature` into a single call. * Accepts the raw base64 or hex signature string returned by * `BrowserWallet.signMessage` / `window.kleverWeb.signMessage` and verifies it * against the signer's KLV address. * * @param message - The original plaintext message that was signed * @param signature - The 64-byte signature as a `Uint8Array` * @param publicKey - The signer's 32-byte Ed25519 public key * @returns A promise resolving to `true` if the signature is valid * * @example * ```typescript * import { cryptoProvider, verifyWalletSignedMessage } from '@klever/connect-crypto' * * const publicKey = await cryptoProvider.addressToBytes(walletAddress) * const sigBytes = Uint8Array.from(atob(signatureBase64), c => c.charCodeAt(0)) * const isValid = await verifyWalletSignedMessage(message, sigBytes, publicKey) * ``` */ declare function verifyWalletSignedMessage(message: string, signature: Uint8Array, publicKey: Uint8Array): Promise; /** * Default implementation of the CryptoProvider interface for Klever blockchain. * * @remarks * This class provides a complete cryptographic provider implementation using Ed25519 * for key generation, signing, and verification. It also handles address encoding/decoding * using bech32 format and supports PEM file operations for private key management. * * This provider is used throughout the Klever Connect SDK for all cryptographic operations * and can be replaced with custom implementations if needed (e.g., hardware wallet providers). * * SECURITY WARNING: This provider handles private keys in memory. For production applications, * consider using hardware wallets or secure enclaves for private key storage. * * @example * ```typescript * // Create a new provider instance * const provider = new DefaultCryptoProvider() * * // Generate a new key pair * const keyPair = await provider.generateKeyPair() * console.log('Address:', keyPair.publicKey.toAddress()) * * // Import an existing private key * const privateKey = provider.importPrivateKey('your-private-key-hex') * const publicKey = await provider.getPublicKey(privateKey) * * // Sign a message * const message = new TextEncoder().encode('Hello, Klever!') * const signature = await provider.signMessage(message, privateKey) * * // Verify a signature * const isValid = await provider.verifySignature(message, signature, publicKey) * ``` */ declare class DefaultCryptoProvider implements CryptoProvider { /** * Generates a new Ed25519 key pair. * * @remarks * Creates a new cryptographically secure key pair suitable for use on the Klever blockchain. * The generated private key should be stored securely. * * SECURITY WARNING: Store the generated private key securely. Never expose it in logs, * network requests, or insecure storage. Consider using hardware wallets or encrypted * storage for production applications. * * @returns A promise that resolves to a KeyPair containing both private and public keys * * @example * ```typescript * const provider = new DefaultCryptoProvider() * const keyPair = await provider.generateKeyPair() * * console.log('Private Key:', keyPair.privateKey.toHex()) * console.log('Public Key:', keyPair.publicKey.toHex()) * console.log('Address:', keyPair.publicKey.toAddress()) * ``` */ generateKeyPair(): Promise; /** * Imports a private key from hex string or bytes. * * @remarks * This method accepts private keys in two formats: * - Hex string (with or without '0x' prefix) * - Uint8Array of 32 bytes * * SECURITY WARNING: Never expose private keys in logs, network requests, or insecure storage. * Ensure private keys are transmitted and stored securely. * * @param key - The private key as a hex string or Uint8Array * @returns A PrivateKey instance * * @throws Error if the key is invalid or not 32 bytes * * @example * ```typescript * const provider = new DefaultCryptoProvider() * * // Import from hex string * const privateKey1 = provider.importPrivateKey('a1b2c3...') * * // Import from hex string with 0x prefix * const privateKey2 = provider.importPrivateKey('0xa1b2c3...') * * // Import from bytes * const privateKey3 = provider.importPrivateKey(new Uint8Array(32)) * ``` */ importPrivateKey(key: string | Uint8Array): PrivateKey; /** * Derives the public key from a private key. * * @remarks * Uses Ed25519 elliptic curve cryptography to derive the public key from the * given private key. The public key can be safely shared and is used for * signature verification and address generation. * * @param privateKey - The private key to derive from * @returns A promise that resolves to the corresponding PublicKey * * @throws Error if the private key is invalid * * @example * ```typescript * const provider = new DefaultCryptoProvider() * const privateKey = provider.importPrivateKey('a1b2c3...') * const publicKey = await provider.getPublicKey(privateKey) * * console.log('Public Key:', publicKey.toHex()) * console.log('Address:', publicKey.toAddress()) * ``` */ getPublicKey(privateKey: PrivateKey): Promise; /** * Signs a message using a private key. * * @remarks * Creates a cryptographic signature that proves the message was signed by the * holder of the private key. The signature can be verified by anyone with the * corresponding public key. * * SECURITY WARNING: Never expose the private key used for signing. * * @param message - The message to sign as a Uint8Array * @param privateKey - The private key used for signing * @returns A promise that resolves to the Signature * * @throws Error if the private key is invalid or signing fails * * @example * ```typescript * const provider = new DefaultCryptoProvider() * const privateKey = provider.importPrivateKey('a1b2c3...') * const message = new TextEncoder().encode('Hello, Klever!') * * const signature = await provider.signMessage(message, privateKey) * console.log('Signature (hex):', signature.toHex()) * console.log('Signature (base64):', signature.toBase64()) * ``` */ signMessage(message: Uint8Array, privateKey: PrivateKey): Promise; /** * Verifies a signature against a message and public key. * * @remarks * Verifies that a signature was created by the holder of the private key * corresponding to the given public key. Returns true if valid, false otherwise. * * This function never throws on invalid signatures - it returns false instead, * making it safe to use in validation logic. * * @param message - The original message that was signed * @param signature - The signature to verify * @param publicKey - The public key used for verification * @returns A promise that resolves to true if the signature is valid, false otherwise * * @example * ```typescript * const provider = new DefaultCryptoProvider() * const message = new TextEncoder().encode('Hello, Klever!') * const signature = SignatureImpl.fromHex('...') * const publicKey = PublicKeyImpl.fromHex('...') * * const isValid = await provider.verifySignature(message, signature, publicKey) * console.log('Signature valid:', isValid) * ``` */ verifySignature(message: Uint8Array, signature: Signature, publicKey: PublicKey): Promise; /** * Converts a Klever address (bech32 format) to its raw bytes representation. * * @remarks * Klever addresses use bech32 encoding (e.g., 'klv1...'). This method decodes * the address to get the underlying public key bytes. * * @param address - The Klever address in bech32 format (e.g., 'klv1...') * @returns A promise that resolves to the 32-byte public key as Uint8Array * * @throws Error if the address is invalid or malformed * * @example * ```typescript * const provider = new DefaultCryptoProvider() * const bytes = await provider.addressToBytes('klv1abc123...') * console.log('Address bytes:', bytes) * ``` */ addressToBytes(address: string): Promise; /** * Converts raw bytes to a Klever address (bech32 format). * * @remarks * Encodes the public key bytes into a bech32-formatted Klever address (e.g., 'klv1...'). * * @param bytes - The 32-byte public key as Uint8Array * @returns A promise that resolves to the Klever address in bech32 format * * @throws Error if the bytes are invalid or not 32 bytes * * @example * ```typescript * const provider = new DefaultCryptoProvider() * const publicKeyBytes = new Uint8Array(32) // Your public key bytes * const address = await provider.bytesToAddress(publicKeyBytes) * console.log('Address:', address) * // Prints: klv1... * ``` */ bytesToAddress(bytes: Uint8Array): Promise; /** * Signs data using a private key hex string. * * @remarks * Convenience method that accepts a private key as a hex string and returns * the signature bytes directly. This is useful for quick signing operations * without creating intermediate objects. * * SECURITY WARNING: Never expose the private key hex string in logs, network * requests, or insecure storage. * * @param data - The data to sign as Uint8Array * @param privateKeyHex - The private key as a hex string * @returns A promise that resolves to the 64-byte signature as Uint8Array * * @throws Error if the private key is invalid or signing fails * * @example * ```typescript * const provider = new DefaultCryptoProvider() * const data = new TextEncoder().encode('Hello, Klever!') * const signatureBytes = await provider.sign(data, 'a1b2c3...') * console.log('Signature bytes:', signatureBytes) * ``` */ sign(data: Uint8Array, privateKeyHex: string): Promise; /** * Imports a private key from PEM format content. * * @remarks * Loads a private key from PEM-formatted content. Supports both encrypted and * unencrypted PEM files. For encrypted files, a password must be provided. * * The PEM file is verified to ensure the private key corresponds to the address * claimed in the PEM header, preventing tampering or mistakes. * * SECURITY WARNINGS: * - Use strong passwords for PEM encryption (minimum 12 characters, mix of letters, numbers, symbols) * - Store PEM files securely with appropriate file permissions * - Never transmit unencrypted PEM files over insecure channels * - Consider using hardware wallets for production applications * * @param pemContent - The PEM file content as a string * @param options - Loading options including password and key index * @returns A promise that resolves to the imported PrivateKey * * @throws Error if the PEM is invalid, password is incorrect, or address verification fails * * @example * ```typescript * const provider = new DefaultCryptoProvider() * * // Load encrypted PEM * const pemContent = '-----BEGIN PRIVATE KEY for klv1...-----\n...' * const privateKey = await provider.importPrivateKeyFromPem(pemContent, { * password: 'your-secure-password', * index: 0 * }) * * // Load unencrypted PEM * const privateKey2 = await provider.importPrivateKeyFromPem(pemContent) * ``` */ importPrivateKeyFromPem(pemContent: string, options?: LoadPemOptions): Promise; /** * Imports a private key from a PEM file (Node.js only). * * @remarks * Convenience method that reads a PEM file from the filesystem and imports the * private key. This method is only available in Node.js environments. * * Supports both encrypted and unencrypted PEM files. For encrypted files, * a password must be provided. * * SECURITY WARNINGS: * - Store PEM files with restrictive permissions (e.g., 600 on Unix systems) * - Use strong passwords for PEM encryption (minimum 12 characters, mix of letters, numbers, symbols) * - Never commit PEM files to version control * - Consider using hardware wallets for production applications * * @param filePath - The path to the PEM file * @param options - Loading options including password and key index * @returns A promise that resolves to the imported PrivateKey * * @throws Error if not in Node.js environment, file cannot be read, or PEM is invalid * * @example * ```typescript * const provider = new DefaultCryptoProvider() * * // Load encrypted PEM file * const privateKey = await provider.importPrivateKeyFromPemFile( * './wallet.pem', * { password: 'your-secure-password' } * ) * * // Load unencrypted PEM file * const privateKey2 = await provider.importPrivateKeyFromPemFile('./wallet.pem') * ``` */ importPrivateKeyFromPemFile(filePath: string, options?: LoadPemOptions): Promise; } /** * Default singleton instance of the CryptoProvider. * * @remarks * This is a pre-instantiated CryptoProvider instance that can be used throughout * the application. It's recommended to use this singleton instance rather than * creating new instances unless you need custom behavior. * * @example * ```typescript * import { cryptoProvider } from '@klever/connect-crypto' * * // Use the default provider * const keyPair = await cryptoProvider.generateKeyPair() * ``` */ declare const cryptoProvider: DefaultCryptoProvider; /** * PEM file utilities for loading and parsing private keys */ interface PemBlock { type: string; headers: Record; bytes: Uint8Array; } /** * Checks if a PEM block is encrypted. * * @remarks * Determines if a PEM block is encrypted by checking for the presence of the * DEK-Info header, which indicates the encryption algorithm used. * * @param block - The PEM block to check * @returns True if the block is encrypted, false otherwise * * @example * ```typescript * const blocks = parsePemBlocks(pemContent) * const isEncrypted = isEncryptedPemBlock(blocks[0]) * * if (isEncrypted) { * console.log('This PEM file requires a password') * } * ``` */ declare function isEncryptedPemBlock(block: PemBlock): boolean; /** * Loads a private key from PEM file content with address verification. * * @remarks * This function parses PEM content and extracts the private key. It performs * address verification to ensure the private key in the PEM file actually * corresponds to the address claimed in the PEM header, preventing tampering * or mistakes in PEM file generation. * * For encrypted PEM files, a password must be provided. The function supports * multiple PEM blocks in a single file and allows selecting a specific block * by index. * * SECURITY WARNINGS: * - Use strong passwords for encrypted PEM files (minimum 12 characters, mix of letters, numbers, symbols) * - Store PEM files with restrictive permissions (e.g., 600 on Unix systems) * - Never transmit unencrypted PEM files over insecure channels * - Never commit PEM files to version control * - Consider using hardware wallets for production applications * - The private key is loaded into memory; ensure your application has appropriate * security measures to protect memory from unauthorized access * * @param content - PEM file content as string * @param options - Loading options including password and key index * @returns A promise that resolves to an object containing the private key bytes and address * * @throws Error if no PEM blocks are found * @throws Error if the index is invalid or out of range * @throws Error if an encrypted key is encountered without a password * @throws Error if the block type is invalid (doesn't start with 'PRIVATE KEY for ') * @throws Error if the private key does not derive to the claimed address (security check) * @throws Error if decryption fails (usually due to incorrect password) * * @example * ```typescript * // Load encrypted PEM * const pemContent = '-----BEGIN PRIVATE KEY for klv1...-----\n...' * const result = await loadPrivateKeyFromPem(pemContent, { * password: 'your-secure-password', * index: 0 * }) * console.log('Address:', result.address) * console.log('Private Key loaded successfully') * * // Load unencrypted PEM * const result2 = await loadPrivateKeyFromPem(pemContent) * ``` */ declare function loadPrivateKeyFromPem(content: string, options?: LoadPemOptions): Promise<{ privateKey: Uint8Array; address: string; }>; /** * Loads a private key from a PEM file on the filesystem (Node.js only). * * @remarks * This is a convenience wrapper that reads a PEM file from the filesystem and * loads the private key. This method is only available in Node.js environments. * * The function performs the same address verification as loadPrivateKeyFromPem * to ensure the private key corresponds to the claimed address. * * SECURITY WARNINGS: * - Store PEM files with restrictive permissions (e.g., 600 on Unix systems) * - Use strong passwords for encrypted PEM files (minimum 12 characters, mix of letters, numbers, symbols) * - Never commit PEM files to version control * - Never share PEM files over insecure channels (use encrypted transfer methods) * - Consider using hardware wallets for production applications * - Ensure the file path doesn't expose sensitive information in logs * - The private key is loaded into memory; ensure your application has appropriate * security measures to protect memory from unauthorized access * * @param filePath - The path to the PEM file (absolute or relative) * @param options - Loading options including password and key index * @returns A promise that resolves to an object containing the private key bytes and address * * @throws Error if not in Node.js environment (browser context) * @throws Error if the file cannot be read * @throws Error if the PEM content is invalid (see loadPrivateKeyFromPem for details) * * @example * ```typescript * // Load encrypted PEM file * const result = await loadPrivateKeyFromPemFile('./wallet.pem', { * password: 'your-secure-password' * }) * console.log('Address:', result.address) * * // Load unencrypted PEM file * const result2 = await loadPrivateKeyFromPemFile('./wallet.pem') * * // Set appropriate file permissions (Unix/Linux/macOS) * // chmod 600 wallet.pem * ``` */ declare function loadPrivateKeyFromPemFile(filePath: string, options?: LoadPemOptions): Promise<{ privateKey: Uint8Array; address: string; }>; declare const DEFAULT_DERIVATION_PATH = "m/44'/690'/0'/0'/0'"; declare const KLEVER_COIN_TYPE = 690; type MnemonicStrength = 128 | 160 | 192 | 224 | 256; interface GenerateMnemonicOptions { strength?: MnemonicStrength; } interface MnemonicToKeyOptions { path?: string; passphrase?: string; } /** * Generates a new BIP39 mnemonic phrase with specified strength. * * @param options - Generation options including strength * @returns A space-separated mnemonic phrase * * @throws Error if strength is not one of the valid values (128, 160, 192, 224, 256) * * @example * ```typescript * // Generate 12-word mnemonic (default) * const mnemonic = generateMnemonicPhrase() * * // Generate 24-word mnemonic * const strongMnemonic = generateMnemonicPhrase({ strength: 256 }) * ``` */ declare function generateMnemonicPhrase(options?: GenerateMnemonicOptions): string; /** * Validates a BIP39 mnemonic phrase. * * @param mnemonic - The mnemonic phrase to validate * @returns True if the mnemonic is valid, false otherwise * * @example * ```typescript * const isValid = isValidMnemonic('abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about') * console.log(isValid) // true * ``` */ declare function isValidMnemonic(mnemonic: string): boolean; /** * Converts a mnemonic phrase to a private key using SLIP-0010 Ed25519 derivation. * * * @param mnemonic - The BIP39 mnemonic phrase * @param options - Options including derivation path and passphrase * @returns The derived private key * * @throws Error if the mnemonic phrase is invalid * @throws Error if the derivation fails or produces an invalid key * * @example * ```typescript * // Derive with default path * const key = mnemonicToPrivateKey('your mnemonic phrase here') * * // Derive with custom path and passphrase * const key2 = mnemonicToPrivateKey('your mnemonic phrase here', { * path: "m/44'/690'/0'/0'/1'", * passphrase: 'optional-passphrase' * }) * ``` */ declare function mnemonicToPrivateKey(mnemonic: string, options?: MnemonicToKeyOptions): PrivateKey; /** * Derives multiple sequential private keys from a mnemonic phrase. * * @remarks * This function takes the base derivation path and increments the last index * to generate multiple keys sequentially. For example, if the path is * "m/44'/690'/0'/0'/0'", it will generate keys at indices 0', 1', 2', etc. * * @param mnemonic - The BIP39 mnemonic phrase * @param count - Number of keys to derive (must be at least 1) * @param options - Options including derivation path and passphrase * @returns Array of derived private keys * * @throws Error if count is less than 1 * @throws Error if the mnemonic phrase is invalid * * @example * ```typescript * // Derive 5 sequential keys starting from default path * const keys = deriveMultipleKeys('your mnemonic here', 5) * // Generates keys at: m/44'/690'/0'/0'/0', m/44'/690'/0'/0'/1', ..., m/44'/690'/0'/0'/4' * * // Derive with custom starting path * const keys2 = deriveMultipleKeys('your mnemonic here', 3, { * path: "m/44'/690'/0'/0'/10'" * }) * // Generates keys at: m/44'/690'/0'/0'/10', m/44'/690'/0'/0'/11', m/44'/690'/0'/0'/12' * ``` */ declare function deriveMultipleKeys(mnemonic: string, count: number, options?: MnemonicToKeyOptions): PrivateKey[]; /** * Builds a BIP44 derivation path for Klever accounts. * * @remarks * Constructs a derivation path following the BIP44 standard: * m/44'/coin_type'/account'/change'/index' * * Where: * - 44' is the BIP44 purpose (hardened) * - coin_type is Klever's registered coin type (690, hardened) * - account' is the account index (hardened) * - change' is 0' for external (receiving) or 1' for internal (change) addresses (hardened) * - index' is the address index (hardened) * * @param account - Account index (default: 0, must be non-negative integer) * @param change - Chain type: 0 for external, 1 for internal (default: 0) * @param index - Address index (default: 0, must be non-negative integer) * @returns The formatted BIP44 derivation path * * @throws Error if account is negative or not an integer * @throws Error if change is not 0 or 1 * @throws Error if index is negative or not an integer * * @example * ```typescript * // Build default path * const path1 = buildDerivationPath() * // Returns: "m/44'/690'/0'/0'/0'" * * // Build path for second account, first address * const path2 = buildDerivationPath(1, 0, 0) * // Returns: "m/44'/690'/1'/0'/0'" * * // Build path for change address * const path3 = buildDerivationPath(0, 1, 5) * // Returns: "m/44'/690'/0'/1'/5'" * ``` */ declare function buildDerivationPath(account?: number, change?: number, index?: number): string; interface Keystore { version: 1; id: string; address: string; crypto: { ciphertext: string; cipherparams: { iv: string; tag: string; }; cipher: 'aes-256-gcm'; kdf: 'scrypt'; kdfparams: { dklen: number; salt: string; n: number; r: number; p: number; }; }; } interface EncryptOptions { scryptN?: number; scryptR?: number; scryptP?: number; } declare const DEFAULT_SCRYPT_PARAMS: { n: number; r: number; p: number; dklen: number; }; /** * Encrypts a private key into a Klever Keystore V1 format. * * @remarks * This function uses the scrypt key derivation function (KDF) with AES-256-GCM authenticated * encryption to securely encrypt a private key with a password. * * Security features: * - Scrypt KDF with configurable parameters (default N=262144 for strong security) * - AES-256-GCM authenticated encryption * - 256-bit encryption key (stronger than AES-128) * - Built-in authentication tag for integrity verification * - Cryptographically random 12-byte IV (unique per encryption, per AES-GCM spec) * - Random 32-byte salt for scrypt KDF * * @param privateKey - The private key to encrypt * @param password - Password to protect the keystore (minimum 8 characters) * @param address - The wallet address associated with this key * @param options - Optional scrypt parameters (N, r, p) for custom security levels * @returns A promise that resolves to the encrypted keystore object * * @throws Error if password is empty or less than 8 characters * @throws Error if scryptN is not a power of 2 * @throws Error if scryptR or scryptP are not positive numbers * * @example * ```typescript * import { generateKeyPair } from '@klever/connect-crypto' * * // Generate a key pair * const { privateKey, publicKey } = await generateKeyPair() * const address = 'klv1...' * * // Encrypt with default parameters (strong security) * const keystore = await encryptToKeystore(privateKey, 'my-secure-password', address) * * // Encrypt with custom parameters (faster, less secure - useful for testing) * const testKeystore = await encryptToKeystore(privateKey, 'password', address, { * scryptN: 4096, // Lower N = faster but less secure * scryptR: 8, * scryptP: 1 * }) * * // Save keystore to file * const keystoreJson = JSON.stringify(keystore, null, 2) * ``` */ declare function encryptToKeystore(privateKey: PrivateKey | Uint8Array, password: string, address: string, options?: EncryptOptions): Promise; /** * Decrypts a Klever Keystore V1 to retrieve the private key. * * @remarks * This function decrypts a keystore encrypted with Klever's V1 format using AES-256-GCM * authenticated encryption. The authentication tag is automatically verified during * decryption, ensuring both the password is correct and the keystore hasn't been tampered with. * * Supported formats: * - Version 1 keystores only * - AES-256-GCM cipher * - Scrypt KDF * * @param keystore - The keystore object or JSON string to decrypt * @param password - The password used to encrypt the keystore * @returns A promise that resolves to the decrypted private key * * @throws Error if keystore version is not 1 * @throws Error if cipher is not 'aes-256-gcm' * @throws Error if KDF is not 'scrypt' * @throws Error if password is incorrect (GCM authentication failed) * @throws Error if keystore is corrupted or tampered with * @throws Error if decrypted private key length is not 32 bytes * * @example * ```typescript * import { cryptoProvider } from '@klever/connect-crypto' * * // Decrypt from keystore object * const privateKey = await decryptKeystore(keystore, 'my-secure-password') * * // Decrypt from JSON string * const keystoreJson = '{"version":1,"id":"...","crypto":{...}}' * const privateKey2 = await decryptKeystore(keystoreJson, 'password') * * // Use the decrypted private key * console.log('Private key hex:', privateKey.toHex()) * const publicKey = await cryptoProvider.getPublicKey(privateKey) * const address = publicKey.toAddress() * ``` */ declare function decryptKeystore(keystore: Keystore | string, password: string): Promise; /** * Checks if a password is correct for a keystore. * * @remarks * This function verifies if a password is correct by attempting to decrypt the keystore. * With AES-256-GCM, authentication is performed during decryption, so we must actually * decrypt to verify the password.. * * @param keystore - The keystore object or JSON string to check * @param password - The password to verify * @returns A promise that resolves to true if password is correct, false otherwise * * @example * ```typescript * // Verify password before using the private key * const isValid = await isPasswordCorrect(keystore, 'my-password') * if (isValid) { * const privateKey = await decryptKeystore(keystore, 'my-password') * console.log('Decryption successful!') * } else { * console.error('Invalid password') * } * * // Quick password validation * if (!await isPasswordCorrect(keystore, userInput)) { * throw new Error('Incorrect password') * } * ``` */ declare function isPasswordCorrect(keystore: Keystore | string, password: string): Promise; interface PathComponent { index: number; hardened: boolean; } /** * Parse a BIP44 derivation path into components * Example: "m/44'/690'/0'/0'/0'" -> [{index: 44, hardened: true}, ...] */ declare function parsePath(path: string): PathComponent[]; declare function getMasterKeyFromSeed(seed: Uint8Array): { key: Uint8Array; chainCode: Uint8Array; }; /** Derive a child key from parent key and chain code * @remarks Important: Ed25519 SLIP-10 requires all path components to be hardened. Non-hardened components will derive keys but the results will NOT be compatible with other SLIP-10 Ed25519 implementations. Always use paths like m/44'/690'/0'/0'/0' (all components ending with '). @param parentKey - Parent private key (32 bytes) @param chainCode - Parent chain code (32 bytes) @param component - Path component with index and hardened flag @returns Derived child key and chain code */ declare function deriveChildKey(parentKey: Uint8Array, chainCode: Uint8Array, component: PathComponent): { key: Uint8Array; chainCode: Uint8Array; }; /** * Derive a private key from seed following a derivation path * * @param seed - The master seed (from mnemonic) * @param path - BIP44 path like "m/44'/690'/0'/0'/0'" * @returns 32-byte Ed25519 private key * * @example * ```typescript * const seed = mnemonicToSeedSync("your mnemonic here", "") * const privateKey = deriveEd25519PrivateKey(seed, "m/44'/690'/0'/0'/0'") * ``` */ declare function deriveEd25519PrivateKey(seed: Uint8Array, path: string): Uint8Array; export { type CryptoProvider, DEFAULT_DERIVATION_PATH, DEFAULT_SCRYPT_PARAMS, DefaultCryptoProvider, type EncryptOptions, type GenerateMnemonicOptions, KLEVER_COIN_TYPE, type KeyPair, type Keystore, type LoadPemOptions, type MnemonicStrength, type MnemonicToKeyOptions, type PathComponent, type PemBlock, type PrivateKey, PrivateKeyImpl, type PublicKey, PublicKeyImpl, type SignableMessage, type Signature, SignatureImpl, buildDerivationPath, cryptoProvider as crypto, cryptoProvider, decryptKeystore, deriveChildKey, deriveEd25519PrivateKey, deriveMultipleKeys, encryptToKeystore, generateKeyPair, generateKeyPairSync, generateMnemonicPhrase, getMasterKeyFromSeed, getPublicKeyFromPrivate, getPublicKeyFromPrivateSync, isEncryptedPemBlock, isPasswordCorrect, isValidMnemonic, loadPrivateKeyFromPem, loadPrivateKeyFromPemFile, mnemonicToPrivateKey, parsePath, prepareKlvMessage, signMessage, signMessageSync, verifySignature, verifySignatureSync, verifyWalletSignedMessage };