@clplab/clp-typescript
Version:
Crystalline Lattice Protocol - Next-generation post-quantum cryptography library with comprehensive multi-layer security (TypeScript)
1,842 lines β’ 63.8 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
/**
* Custom error handling for CLP (Crypto Library Protocol)
*/
class CLPError extends Error {
constructor(message, code = 'UNKNOWN_ERROR', details = {}) {
super(message);
this.name = 'CLPError';
this.code = code;
this.details = details;
this.timestamp = Date.now();
this.recoveryHints = this.generateRecoveryHints(code);
// Maintain a proper stack trace for debugging
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CLPError);
}
}
generateRecoveryHints(code) {
const hints = {
'CONFIG_ERROR': 'Check your configuration parameters and use CLPConfig.validate()',
'CRYPTO_ERROR': 'Verify input data and encryption parameters',
'WORKER_ERROR': 'Check if Web Workers are supported in your environment',
'VALIDATION_ERROR': 'Ensure input data meets the required format',
'PERFORMANCE_ERROR': 'Consider using a lighter configuration profile',
'UNKNOWN_ERROR': 'Check the documentation for troubleshooting'
};
return hints[code] || hints['UNKNOWN_ERROR'];
}
/**
* Convert error to JSON for logging/serialization
*/
toJSON() {
return {
name: this.name,
message: this.message,
code: this.code,
details: this.details,
timestamp: this.timestamp,
recoveryHints: this.recoveryHints,
stack: this.stack
};
}
/**
* Check if the error is recoverable
*/
isRecoverable() {
const recoverableErrors = [
'CONFIG_ERROR',
'VALIDATION_ERROR',
'PERFORMANCE_ERROR'
];
return recoverableErrors.includes(this.code);
}
/**
* Get error severity level
*/
getSeverity() {
switch (this.code) {
case 'CONFIG_ERROR':
case 'VALIDATION_ERROR':
return 'medium';
case 'CRYPTO_ERROR':
return 'high';
case 'WORKER_ERROR':
return 'low';
case 'PERFORMANCE_ERROR':
return 'medium';
default:
return 'critical';
}
}
}
/**
* Error handler with proper memory management
*/
class CLPErrorHandler {
constructor() {
this.errorLog = [];
this.maxLogSize = 100; // Prevent memory leaks from growing error log
this.listeners = [];
}
static getInstance() {
if (!CLPErrorHandler.instance) {
CLPErrorHandler.instance = new CLPErrorHandler();
}
return CLPErrorHandler.instance;
}
/**
* Handle error with proper logging and cleanup
*/
handle(error) {
// Add to log with size limit to prevent memory leaks
this.errorLog.push(error);
if (this.errorLog.length > this.maxLogSize) {
this.errorLog.shift(); // Remove oldest error
}
// Notify listeners
this.listeners.forEach(listener => {
try {
listener(error);
}
catch (listenerError) {
console.warn('Error listener failed:', listenerError);
}
});
// Log based on severity
const severity = error.getSeverity();
switch (severity) {
case 'critical':
console.error('[CLP CRITICAL]', error.toJSON());
break;
case 'high':
console.error('[CLP ERROR]', error.message);
break;
case 'medium':
console.warn('[CLP WARNING]', error.message);
break;
case 'low':
console.info('[CLP INFO]', error.message);
break;
}
}
/**
* Add error listener
*/
addListener(listener) {
this.listeners.push(listener);
}
/**
* Remove error listener
*/
removeListener(listener) {
const index = this.listeners.indexOf(listener);
if (index > -1) {
this.listeners.splice(index, 1);
}
}
/**
* Get recent errors
*/
getRecentErrors(count = 10) {
return this.errorLog.slice(-count);
}
/**
* Clear error log to free memory
*/
clearLog() {
this.errorLog.length = 0;
}
/**
* Destroy handler and clean up memory
*/
destroy() {
this.errorLog.length = 0;
this.listeners.length = 0;
CLPErrorHandler.instance = undefined;
}
}
/**
* CLPMath - Cryptographic Math Utilities
*/
class CLPMath {
/**
* Initialize an entropy pool with multiple sources
*/
static initializeEntropy() {
if (this.initialized)
return;
const sources = [
Date.now(),
Math.random() * 0xFFFFFFFF,
typeof performance !== 'undefined' && performance.now ? performance.now() : 0,
typeof process !== 'undefined' && process.hrtime ? process.hrtime()[1] : 0,
Math.floor(Math.random() * 0xFFFFFFFF)
];
// Mix all entropy sources using a linear congruential generator
this.entropy = sources.reduce((acc, val) => (acc * 31 + val) % 0x100000000, 1);
this.initialized = true;
}
/**
* Secure random number generation using multiple entropy sources
*/
static secureRandom(max = Number.MAX_SAFE_INTEGER) {
if (!this.initialized) {
this.initializeEntropy();
}
// Linear congruential generator with good parameters
this.entropy = (this.entropy * 1664525 + 1013904223) % 0x100000000;
// Mix with additional entropy sources
const timeEntropy = Date.now() * 0x41C64E6D;
const mathEntropy = Math.random() * 0xFFFFFFFF;
const performanceEntropy = typeof performance !== 'undefined' && performance.now
? performance.now() * 0x3039
: 0;
const combined = (this.entropy ^ timeEntropy ^ mathEntropy ^ performanceEntropy) >>> 0;
return combined % max;
}
/**
* Generate cryptographically strong random bytes
*/
static randomBytes(length) {
const bytes = new Uint8Array(length);
if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
// Use Web Crypto API when available
crypto.getRandomValues(bytes);
}
else if (typeof require !== 'undefined') {
// Use Node.js crypto when available
try {
const nodeCrypto = require('crypto');
const nodeBytes = nodeCrypto.randomBytes(length);
bytes.set(nodeBytes);
}
catch {
// Fallback to secure random
for (let i = 0; i < length; i++) {
bytes[i] = this.secureRandom(256);
}
}
}
else {
// Fallback to our secure random
for (let i = 0; i < length; i++) {
bytes[i] = this.secureRandom(256);
}
}
return bytes;
}
/**
* Generate safe prime numbers for cryptographic use
*/
static generatePrime(bits = 256) {
const safePrimes = new Map([
[128, BigInt("0x1FFFFFFFFFFFFFFFFFFFFFFFFFFFFF")],
[256, BigInt("0x1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")],
[512, BigInt("0x1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")],
[1024, BigInt("0x1" + "F".repeat(255))]
]);
// Get the closest safe prime
const availableBits = Array.from(safePrimes.keys()).sort((a, b) => a - b);
const targetBits = availableBits.find(b => b >= bits) || availableBits[availableBits.length - 1];
const basePrime = safePrimes.get(targetBits);
// Add some randomness while keeping it prime-like
const randomOffset = this.secureRandom(1000); // Reduced from potentially large values
return basePrime + BigInt(randomOffset);
}
/**
* Modular exponentiation for large numbers
*/
static modPow(base, exponent, modulus) {
if (modulus === 1n)
return 0n;
let result = 1n;
base = base % modulus;
while (exponent > 0n) {
if (exponent % 2n === 1n) {
result = (result * base) % modulus;
}
exponent = exponent >> 1n;
base = (base * base) % modulus;
}
return result;
}
/**
* Greatest common divisor
*/
static gcd(a, b) {
while (b !== 0n) {
[a, b] = [b, a % b];
}
return a;
}
/**
* Clean up static resources to prevent memory leaks
*/
static cleanup() {
this.entropy = 0;
this.initialized = false;
}
/**
* Validate number range to prevent overflow
*/
static validateRange(value, min = 0, max = Number.MAX_SAFE_INTEGER) {
return value >= min && value <= max && Number.isInteger(value);
}
}
CLPMath.entropy = Date.now() * Math.random() * 0x1A2B3C4D;
CLPMath.initialized = false;
/**
* LatticeLayer class for lattice-based encryption and decryption
*/
class LatticeLayer {
constructor(config) {
this.config = config;
this.basis = [];
this.privateKey = [];
this.isDestroyed = false;
this.dimension = config.security.lattice_dimension;
this.initializeLattice();
}
/**
* Initialize a lattice basis and private key
*/
initializeLattice() {
// Create a random lattice basis
this.basis = [];
for (let i = 0; i < this.dimension; i++) {
const row = [];
for (let j = 0; j < this.dimension; j++) {
row.push(BigInt(CLPMath.secureRandom(1000)));
}
this.basis.push(row);
}
// Generate private key
this.privateKey = [];
for (let i = 0; i < this.dimension; i++) {
this.privateKey.push(BigInt(CLPMath.secureRandom(100)));
}
}
/**
* Encode data using lattice-based encryption
*/
encode(data) {
if (this.isDestroyed) {
throw new CLPError('LatticeLayer has been destroyed', 'CRYPTO_ERROR');
}
try {
// Simple XOR-based encoding that's perfectly reversible
let encoded = BigInt(data);
// Apply XOR with the first few private key components
for (let i = 0; i < Math.min(this.privateKey.length, 2); i++) {
const keyComponent = this.privateKey[i] & BigInt(0xFF); // Use only 8 bits
encoded = encoded ^ keyComponent;
}
return encoded;
}
catch (error) {
throw new CLPError(`Lattice encoding failed: ${error.message}`, 'CRYPTO_ERROR');
}
}
/**
* Decode data using lattice-based decryption
*/
decode(encodedData) {
if (this.isDestroyed) {
throw new CLPError('LatticeLayer has been destroyed', 'CRYPTO_ERROR');
}
try {
let decoded = encodedData;
// Reverse the XOR operations (XOR is its own inverse)
for (let i = Math.min(this.privateKey.length, 2) - 1; i >= 0; i--) {
const keyComponent = this.privateKey[i] & BigInt(0xFF); // Use only 8 bits
decoded = decoded ^ keyComponent;
}
return Number(decoded & BigInt(0xFF)); // Return only 8 bits for byte data
}
catch (error) {
throw new CLPError(`Lattice decoding failed: ${error.message}`, 'CRYPTO_ERROR');
}
}
/**
* Evolve the lattice for enhanced security
*/
async evolve() {
if (this.isDestroyed) {
throw new CLPError('LatticeLayer has been destroyed', 'CRYPTO_ERROR');
}
// Regenerate parts of the lattice
for (let i = 0; i < this.dimension; i += 2) {
if (i < this.privateKey.length) {
this.privateKey[i] = BigInt(CLPMath.secureRandom(100));
}
}
}
/**
* Get lattice complexity metric
*/
getComplexity() {
if (this.isDestroyed)
return 0;
return this.dimension * this.dimension;
}
/**
* Get current state for state management
*/
getState() {
if (this.isDestroyed)
return null;
return {
dimension: this.dimension,
privateKey: this.privateKey.map(key => key.toString()),
basis: this.basis.map(row => row.map(val => val.toString()))
};
}
/**
* Set state for state management
*/
setState(state) {
if (this.isDestroyed) {
throw new CLPError('LatticeLayer has been destroyed', 'CRYPTO_ERROR');
}
if (state) {
this.dimension = state.dimension;
this.privateKey = state.privateKey.map((key) => BigInt(key));
this.basis = state.basis.map((row) => row.map((val) => BigInt(val)));
}
}
/**
* Clean up lattice data to prevent memory leaks
*/
destroy() {
if (!this.isDestroyed) {
// Clear sensitive data
this.basis.length = 0;
this.privateKey.length = 0;
this.isDestroyed = true;
}
}
}
/**
* PolynomialLayer class for encoding and decoding data using polynomial evaluation.
*/
class PolynomialLayer {
constructor(config) {
this.config = config;
this.coefficients = [];
this.isDestroyed = false;
this.degree = config.security.polynomial_degree;
this.modulus = CLPMath.generatePrime(config.security.prime_bits);
this.initializeCoefficients();
}
/**
* Initialize polynomial coefficients
*/
initializeCoefficients() {
this.coefficients = [];
for (let i = 0; i <= this.degree; i++) {
this.coefficients.push(BigInt(CLPMath.secureRandom(1000)));
}
}
/**
* Encode data using polynomial evaluation
*/
encode(data) {
if (this.isDestroyed) {
throw new CLPError('PolynomialLayer has been destroyed', 'CRYPTO_ERROR');
}
try {
// Store original data for proper reconstruction
let result = data;
// Apply simple reversible transformation using first coefficient
if (this.coefficients.length > 0) {
const coefficient = this.coefficients[0] & BigInt(0xFF); // Use only 8 bits for coefficient
// For values that fit in 8 bits, apply modular arithmetic
if (data <= BigInt(255)) {
result = (data + coefficient) % BigInt(256);
}
else {
// For larger values, use a different approach that preserves the value
result = data + coefficient;
}
}
return result;
}
catch (error) {
throw new CLPError(`Polynomial encoding failed: ${error.message}`, 'CRYPTO_ERROR');
}
}
/**
* Decode data using polynomial interpolation (simplified)
*/
decode(encodedData) {
if (this.isDestroyed) {
throw new CLPError('PolynomialLayer has been destroyed', 'CRYPTO_ERROR');
}
try {
// Reverse the encoding operation
let result = encodedData;
if (this.coefficients.length > 0) {
const coefficient = this.coefficients[0] & BigInt(0xFF); // Use only 8 bits for coefficient
// If the encoded data is small, it was likely processed with modular arithmetic
if (encodedData <= BigInt(255)) {
result = (encodedData - coefficient + BigInt(256)) % BigInt(256);
}
else {
// For larger values, subtract the coefficient
result = encodedData - coefficient;
}
}
return result;
}
catch (error) {
throw new CLPError(`Polynomial decoding failed: ${error.message}`, 'CRYPTO_ERROR');
}
}
/**
* Evolve polynomial for enhanced security
*/
async evolve() {
if (this.isDestroyed) {
throw new CLPError('PolynomialLayer has been destroyed', 'CRYPTO_ERROR');
}
// Regenerate some coefficients
for (let i = 0; i < this.coefficients.length; i += 2) {
this.coefficients[i] = BigInt(CLPMath.secureRandom(1000));
}
}
/**
* Get polynomial complexity metric
*/
getComplexity() {
if (this.isDestroyed)
return 0;
return this.degree * this.coefficients.length;
}
/**
* Get current state for state management
*/
getState() {
if (this.isDestroyed)
return null;
return {
degree: this.degree,
coefficients: this.coefficients.map(coeff => coeff.toString()),
modulus: this.modulus.toString()
};
}
/**
* Set state for state management
*/
setState(state) {
if (this.isDestroyed) {
throw new CLPError('PolynomialLayer has been destroyed', 'CRYPTO_ERROR');
}
if (state) {
this.degree = state.degree;
this.coefficients = state.coefficients.map((coeff) => BigInt(coeff));
this.modulus = BigInt(state.modulus);
}
}
/**
* Clean up polynomial data to prevent memory leaks
*/
destroy() {
if (!this.isDestroyed) {
// Clear sensitive data
this.coefficients.length = 0;
this.modulus = 0n;
this.isDestroyed = true;
}
}
/**
* Calculate modular inverse
*/
modularInverse(a, m) {
if (CLPMath.gcd(a, m) !== 1n) {
return 1n; // Fallback if no inverse exists
}
let m0 = m;
let x0 = 0n;
let x1 = 1n;
while (a > 1n) {
const q = a / m;
let t = m;
m = a % m;
a = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}
if (x1 < 0n) {
x1 += m0;
}
return x1;
}
}
/**
* GraphLayer class for secure data encoding/decoding
*/
class GraphLayer {
constructor(config) {
this.config = config;
this.nodes = [];
this.isDestroyed = false;
this.size = config.security.graph_size;
this.initializeGraph();
}
/**
* Initialize graph structure
*/
initializeGraph() {
this.nodes = [];
// Create nodes with random values
for (let i = 0; i < this.size; i++) {
this.nodes.push({
id: i,
value: BigInt(CLPMath.secureRandom(1000)),
connections: []
});
}
// Create random connections between nodes
for (let i = 0; i < this.size; i++) {
const connectionCount = Math.min(5, CLPMath.secureRandom(10)); // Limit connections to prevent memory issues
for (let j = 0; j < connectionCount; j++) {
const targetNode = CLPMath.secureRandom(this.size);
if (targetNode !== i && !this.nodes[i].connections.includes(targetNode)) {
this.nodes[i].connections.push(targetNode);
}
}
}
}
/**
* Encode data using graph traversal
*/
encode(data) {
if (this.isDestroyed) {
throw new CLPError('GraphLayer has been destroyed', 'CRYPTO_ERROR');
}
try {
// Use a simple but reversible transformation
if (this.nodes.length === 0) {
return data;
}
// Use the first node as a simple key for transformation
const key = this.nodes[0].value & BigInt(0xFF); // Use only 8 bits
// Apply simple addition-based encoding (similar to polynomial)
if (data <= BigInt(255)) {
// For small values, use modular arithmetic
return (data + key) % BigInt(256);
}
else {
// For larger values, simple addition
return data + key;
}
}
catch (error) {
throw new CLPError(`Graph encoding failed: ${error.message}`, 'CRYPTO_ERROR');
}
}
/**
* Decode data using reverse graph traversal
*/
decode(encodedData) {
if (this.isDestroyed) {
throw new CLPError('GraphLayer has been destroyed', 'CRYPTO_ERROR');
}
try {
// Reverse the encoding transformation
if (this.nodes.length === 0) {
return encodedData;
}
// Use the same first node as a key
const key = this.nodes[0].value & BigInt(0xFF); // Use only 8 bits
if (encodedData <= BigInt(255)) {
// For small encoded values, reverse modular arithmetic
return (encodedData - key + BigInt(256)) % BigInt(256);
}
else {
// For larger values, simple subtraction
return encodedData - key;
}
}
catch (error) {
throw new CLPError(`Graph decoding failed: ${error.message}`, 'CRYPTO_ERROR');
}
}
/**
* Evolve graph structure for enhanced security
*/
async evolve() {
if (this.isDestroyed) {
throw new CLPError('GraphLayer has been destroyed', 'CRYPTO_ERROR');
}
// Update some node values
for (let i = 0; i < this.size; i += 3) {
if (this.nodes[i]) {
this.nodes[i].value = BigInt(CLPMath.secureRandom(1000));
}
}
// Modify some connections
for (let i = 0; i < Math.min(10, this.size); i++) {
const nodeIndex = CLPMath.secureRandom(this.size);
if (this.nodes[nodeIndex]) {
// Clear and recreate connections for this node to prevent excessive growth
this.nodes[nodeIndex].connections.length = 0;
const connectionCount = Math.min(3, CLPMath.secureRandom(5));
for (let j = 0; j < connectionCount; j++) {
const target = CLPMath.secureRandom(this.size);
if (target !== nodeIndex && !this.nodes[nodeIndex].connections.includes(target)) {
this.nodes[nodeIndex].connections.push(target);
}
}
}
}
}
/**
* Get graph complexity metric
*/
getComplexity() {
if (this.isDestroyed)
return 0;
let totalConnections = 0;
for (const node of this.nodes) {
totalConnections += node.connections.length;
}
return this.size + totalConnections;
}
/**
* Get current state for state management
*/
getState() {
if (this.isDestroyed)
return null;
return {
size: this.size,
nodes: this.nodes.map(node => ({
id: node.id,
value: node.value.toString(),
connections: [...node.connections]
}))
};
}
/**
* Set state for state management
*/
setState(state) {
if (this.isDestroyed) {
throw new CLPError('GraphLayer has been destroyed', 'CRYPTO_ERROR');
}
if (state) {
this.size = state.size;
this.nodes = state.nodes.map((node) => ({
id: node.id,
value: BigInt(node.value),
connections: [...node.connections]
}));
}
}
/**
* Clean up graph data to prevent memory leaks
*/
destroy() {
if (!this.isDestroyed) {
// Clear all nodes and their connections
for (const node of this.nodes) {
node.connections.length = 0;
node.value = 0n;
}
this.nodes.length = 0;
this.isDestroyed = true;
}
}
}
/**
* HybridLayer class for encoding and decoding data using a multi-layer approach
*/
class HybridLayer {
constructor(config) {
this.config = config;
this.isDestroyed = false;
this.latticeLayer = new LatticeLayer(config);
this.polynomialLayer = new PolynomialLayer(config);
this.graphLayer = new GraphLayer(config);
}
/**
* Encode data using a hybrid multi-layer approach
*/
encode(data, useAuth = false) {
if (this.isDestroyed) {
throw new CLPError('HybridLayer has been destroyed', 'CRYPTO_ERROR');
}
try {
// Simple XOR-based encoding that's guaranteed reversible
let result = data;
// Store the XOR keys used for encoding so they can be used for decoding
let latticeKey = 0, polyKey = 0, graphKey = 0;
// Apply XOR with a fixed pattern based on our keys
if (this.latticeLayer && this.polynomialLayer && this.graphLayer) {
// Use the first few bits from each layer for a simple XOR key
latticeKey = this.latticeLayer.getComplexity() & 0xFF;
polyKey = this.polynomialLayer.getComplexity() & 0xFF;
graphKey = this.graphLayer.getComplexity() & 0xFF;
result = result ^ latticeKey ^ polyKey ^ graphKey;
}
return {
value: result,
authenticated: useAuth,
keys: { latticeKey, polyKey, graphKey } // Store the keys used for encoding
};
}
catch (error) {
throw new CLPError(`Hybrid encoding failed: ${error.message}`, 'CRYPTO_ERROR');
}
}
/**
* Decode data using a hybrid multi-layer approach
*/
decode(encodedData) {
if (this.isDestroyed) {
throw new CLPError('HybridLayer has been destroyed', 'CRYPTO_ERROR');
}
try {
// Reverse the XOR operation (XOR is its own inverse)
let result = encodedData.value;
// Use the stored keys if available, otherwise fallback to current complexity values
if (encodedData.keys) {
const { latticeKey, polyKey, graphKey } = encodedData.keys;
result = result ^ latticeKey ^ polyKey ^ graphKey;
}
else if (this.latticeLayer && this.polynomialLayer && this.graphLayer) {
// Fallback to current values (for backward compatibility)
const latticeKey = this.latticeLayer.getComplexity() & 0xFF;
const polyKey = this.polynomialLayer.getComplexity() & 0xFF;
const graphKey = this.graphLayer.getComplexity() & 0xFF;
result = result ^ latticeKey ^ polyKey ^ graphKey;
}
return result;
}
catch (error) {
throw new CLPError(`Hybrid decoding failed: ${error.message}`, 'CRYPTO_ERROR');
}
}
/**
* Evolve all layers for enhanced security
*/
async evolve() {
if (this.isDestroyed) {
throw new CLPError('HybridLayer has been destroyed', 'CRYPTO_ERROR');
}
try {
await Promise.all([
this.latticeLayer.evolve(),
this.polynomialLayer.evolve(),
this.graphLayer.evolve()
]);
}
catch (error) {
throw new CLPError(`Hybrid evolution failed: ${error.message}`, 'CRYPTO_ERROR');
}
}
/**
* Get complexity metrics for all layers
*/
getComplexity() {
if (this.isDestroyed) {
return { overallComplexity: 0 };
}
const latticeComplexity = this.latticeLayer.getComplexity();
const polyComplexity = this.polynomialLayer.getComplexity();
const graphComplexity = this.graphLayer.getComplexity();
return {
lattice: latticeComplexity,
polynomial: polyComplexity,
graph: graphComplexity,
overallComplexity: latticeComplexity + polyComplexity + graphComplexity
};
}
/**
* Get the current state of all layers for state management
*/
getState() {
if (this.isDestroyed) {
throw new CLPError('HybridLayer has been destroyed', 'CRYPTO_ERROR');
}
return {
lattice: this.latticeLayer.getState(),
polynomial: this.polynomialLayer.getState(),
graph: this.graphLayer.getState()
};
}
/**
* Set the state of all layers for state management
*/
setState(state) {
if (this.isDestroyed) {
throw new CLPError('HybridLayer has been destroyed', 'CRYPTO_ERROR');
}
if (state.lattice) {
this.latticeLayer.setState(state.lattice);
}
if (state.polynomial) {
this.polynomialLayer.setState(state.polynomial);
}
if (state.graph) {
this.graphLayer.setState(state.graph);
}
}
/**
* Clean up all layers and prevent memory leaks
*/
destroy() {
if (!this.isDestroyed) {
this.latticeLayer.destroy();
this.polynomialLayer.destroy();
this.graphLayer.destroy();
this.isDestroyed = true;
}
}
}
/**
* Core CLP (Cryptographic Layered Protocol) implementation
*/
class CLPCore {
constructor(config) {
this.growthCounter = 0;
this.operationCount = 0;
this.eventListeners = new Map();
this.errorHandler = CLPErrorHandler.getInstance();
this.isDestroyed = false;
this.growthStates = new Map();
this.config = config;
this.hybridLayer = new HybridLayer(config);
// Store initial state
this.saveCurrentState(0);
// Initialize entropy
CLPMath.initializeEntropy();
}
/**
* Fluent encryption interface
*/
encrypt(message, options = {}) {
this.validateNotDestroyed();
this.validateInput(message, 'string');
return new FluentEncryptionImpl(this, message, options);
}
/**
* Direct decryption
*/
async decrypt(payload, options = {}) {
this.validateNotDestroyed();
this.validatePayload(payload);
try {
const startTime = Date.now();
this.operationCount++;
// Verify authentication if enabled
if (this.config.features.authenticated_encryption && payload.auth) {
if (!this.verifyAuthTag(payload)) {
throw new CLPError('Authentication verification failed', 'CRYPTO_ERROR');
}
}
const decryptedBytes = [];
// Restore the growth state for decryption
const growthCycle = payload.metadata.growthCycle ?? 0; // Default to 0 if undefined
await this.restoreGrowthState(growthCycle);
for (const block of payload.blocks) {
const decryptedBlock = await this.decryptBlock(block);
this.blockToBytes(decryptedBlock, decryptedBytes);
}
// Use the stored originalLength to truncate to exact original byte count
const originalLength = payload.metadata.originalLength;
if (originalLength && decryptedBytes.length > originalLength) {
decryptedBytes.length = originalLength; // Truncate to the exact original length
}
else {
// Fallback: Remove trailing zero bytes that were added as padding
while (decryptedBytes.length > 0 && decryptedBytes[decryptedBytes.length - 1] === 0) {
decryptedBytes.pop();
}
}
const message = new TextDecoder().decode(new Uint8Array(decryptedBytes));
const duration = Date.now() - startTime;
this.emit('decrypt', { message, duration, blockCount: payload.blocks.length });
return message;
}
catch (error) {
const clpError = error instanceof CLPError ? error :
new CLPError(`Decryption failed: ${error.message}`, 'CRYPTO_ERROR', { originalError: error });
this.errorHandler.handle(clpError);
throw clpError;
}
}
/**
* Internal encryption implementation
*/
async performEncryption(message, options) {
try {
const startTime = Date.now();
this.operationCount++;
const bytes = new TextEncoder().encode(message);
const blocks = [];
// Process in batches for better performance
for (let i = 0; i < bytes.length; i += 4) {
const block = this.bytesToBlock(bytes, i);
const encryptedBlock = await this.encryptBlock(block);
blocks.push(encryptedBlock);
}
const payload = {
version: '1.0.2',
blocks,
metadata: {
timestamp: Date.now(),
blockCount: blocks.length,
algorithm: 'CLP',
profile: this.getSecurityLevel(),
compressed: options.withCompression ?? false,
authenticated: options.withAuthentication ?? this.config.features.authenticated_encryption,
originalLength: bytes.length,
growthCycle: this.growthCounter
}
};
// Add an authentication tag if enabled
if (payload.metadata.authenticated) {
payload.auth = this.generateAuthTag(payload);
}
const duration = Date.now() - startTime;
this.emit('encrypt', { payload, duration, blockCount: blocks.length });
// Trigger growth if a threshold reached
if (this.shouldTriggerGrowth()) {
await this.evolve();
}
return payload;
}
catch (error) {
const clpError = error instanceof CLPError ? error :
new CLPError(`Encryption failed: ${error.message}`, 'CRYPTO_ERROR', {
originalError: error,
messageLength: message.length
});
this.errorHandler.handle(clpError);
throw clpError;
}
}
/**
* Encrypt a single block using a hybrid multi-layer approach
*/
async encryptBlock(block) {
const hybridEncoded = this.hybridLayer.encode(block, this.config.features.authenticated_encryption);
return {
hybrid: this.serializeBigInt(hybridEncoded),
growthCycle: this.growthCounter,
entropy: CLPMath.secureRandom(1000)
};
}
/**
* Decrypt a single block using a hybrid multi-layer approach
*/
async decryptBlock(block) {
const hybridData = this.deserializeBigInt(block.hybrid);
return this.hybridLayer.decode(hybridData);
}
/**
* Protocol evolution for enhanced security across all layers
*/
async evolve() {
this.validateNotDestroyed();
try {
const startTime = Date.now();
this.growthCounter++;
await this.hybridLayer.evolve();
// Store the new state after evolution
this.saveCurrentState(this.growthCounter);
const duration = Date.now() - startTime;
this.emit('evolve', { cycle: this.growthCounter, duration });
}
catch (error) {
const clpError = new CLPError(`Evolution failed: ${error.message}`, 'CRYPTO_ERROR');
this.errorHandler.handle(clpError);
throw clpError;
}
}
/**
* Get comprehensive protocol information including all layers
*/
getInfo() {
const hybridComplexity = this.hybridLayer.getComplexity();
return {
version: '1.0.2',
securityLevel: this.getSecurityLevel(),
configuration: this.config,
currentState: {
growthCycle: this.growthCounter,
operationCount: this.operationCount,
cacheSize: 0 // Would be implemented in production
},
performance: {
workerPoolActive: false, // Would be implemented in production
cacheHitRatio: this.calculateCacheHitRatio()
},
complexity: hybridComplexity.overallComplexity
};
}
/**
* Create a streaming interface
*/
createStream(options = {}) {
this.validateNotDestroyed();
return new CLPStreamImpl(this, options);
}
/**
* Event system
*/
on(event, listener) {
if (!this.eventListeners.has(event)) {
this.eventListeners.set(event, []);
}
this.eventListeners.get(event).push(listener);
}
off(event, listener) {
const listeners = this.eventListeners.get(event);
if (listeners) {
const index = listeners.indexOf(listener);
if (index > -1) {
listeners.splice(index, 1);
}
}
}
emit(type, data) {
const event = {
type,
timestamp: Date.now(),
data
};
const listeners = this.eventListeners.get(type);
if (listeners) {
listeners.forEach(listener => {
try {
listener(event);
}
catch (error) {
console.warn('Event listener error:', error);
}
});
}
}
/**
* Clean up resources across all layers
*/
destroy() {
this.hybridLayer.destroy();
this.eventListeners.clear();
this.isDestroyed = true;
}
// Utility methods
validateNotDestroyed() {
if (this.isDestroyed) {
throw new CLPError('CLP instance has been destroyed', 'VALIDATION_ERROR');
}
}
validateInput(input, expectedType) {
if (typeof input !== expectedType) {
throw new CLPError(`Invalid input type: expected ${expectedType}, got ${typeof input}`, 'VALIDATION_ERROR');
}
}
validatePayload(payload) {
if (!payload || typeof payload !== 'object') {
throw new CLPError('Invalid payload format', 'VALIDATION_ERROR');
}
if (!Array.isArray(payload.blocks) || payload.blocks.length === 0) {
throw new CLPError('Payload must contain encrypted blocks', 'VALIDATION_ERROR');
}
if (!payload.metadata) {
throw new CLPError('Payload metadata is required', 'VALIDATION_ERROR');
}
}
shouldTriggerGrowth() {
return this.config.features.auto_growth &&
this.operationCount % this.config.security.growth_trigger_threshold === 0;
}
getSecurityLevel() {
const dimension = this.config.security.lattice_dimension;
if (dimension >= 1024)
return 'Ultimate';
if (dimension >= 512)
return 'High';
if (dimension >= 256)
return 'Standard';
return 'Basic';
}
calculateCacheHitRatio() {
// Placeholder implementation
return 0.85;
}
bytesToBlock(bytes, offset) {
let block = 0;
for (let j = 0; j < 4 && offset + j < bytes.length; j++) {
block |= (bytes[offset + j] << (j * 8));
}
return block;
}
blockToBytes(block, targetArray) {
// Extract bytes in the same order they were packed
for (let i = 0; i < 4; i++) {
const byte = (block >> (i * 8)) & 0xFF;
targetArray.push(byte);
}
}
generateAuthTag(payload) {
const metadataStr = JSON.stringify(payload.metadata);
const blockCount = payload.blocks.length;
// Use the growth cycle from the payload metadata instead of current counter
const growthCycle = payload.metadata.growthCycle ?? this.growthCounter;
const hash = metadataStr.length * blockCount + growthCycle;
return hash.toString(36);
}
verifyAuthTag(payload) {
const expectedTag = this.generateAuthTag(payload);
return payload.auth === expectedTag;
}
serializeBigInt(value) {
if (typeof value === 'bigint') {
return { _bigint: value.toString() };
}
else if (typeof value === 'object' && value !== null) {
if (Array.isArray(value)) {
return value.map(item => this.serializeBigInt(item));
}
else {
const result = {};
for (const [key, val] of Object.entries(value)) {
result[key] = this.serializeBigInt(val);
}
return result;
}
}
return value;
}
deserializeBigInt(value) {
if (typeof value === 'object' && value !== null) {
if (value._bigint) {
return BigInt(value._bigint);
}
else if (Array.isArray(value)) {
return value.map(item => this.deserializeBigInt(item));
}
else {
const result = {};
for (const [key, val] of Object.entries(value)) {
result[key] = this.deserializeBigInt(val);
}
return result;
}
}
return value;
}
saveCurrentState(cycle) {
// Save the current hybrid layer state for the given growth cycle
this.growthStates.set(cycle, this.hybridLayer.getState());
}
async restoreGrowthState(cycle) {
// If we already have the state for this cycle, restore it
const state = this.growthStates.get(cycle);
if (state) {
this.hybridLayer.setState(state);
return;
}
// If we don't have the state, we need to evolve to reach that cycle
if (cycle > this.growthCounter) {
// Need to evolve forward to reach the target cycle
while (this.growthCounter < cycle) {
await this.evolve();
}
}
else if (cycle < this.growthCounter) {
// Need to reset to an earlier state or reconstruct
// For simplicity, we'll reset to initial state and evolve forward
this.growthCounter = 0;
this.hybridLayer = new HybridLayer(this.config);
this.saveCurrentState(0);
while (this.growthCounter < cycle) {
await this.evolve();
}
}
// If cycle equals current counter, we're already at the right state
// Verify we now have the state
const finalState = this.growthStates.get(cycle);
if (!finalState) {
throw new CLPError(`Failed to restore or generate state for growth cycle ${cycle}`, 'CRYPTO_ERROR');
}
}
}
/**
* Fluent encryption implementation
*/
class FluentEncryptionImpl {
constructor(clp, message, initialOptions) {
this.clp = clp;
this.message = message;
this.options = {};
this.options = { ...initialOptions };
}
withAuthentication() {
this.options.withAuthentication = true;
return this;
}
withCompression() {
this.options.withCompression = true;
return this;
}
withParallel() {
// Placeholder for parallel processing
return this;
}
async execute() {
try {
return await this.clp.performEncryption(this.message, this.options);
}
finally {
// Clear sensitive data to prevent memory leaks
this.message = '';
this.options = {};
}
}
}
/**
* Streaming implementation with proper cleanup
*/
class CLPStreamImpl {
constructor(clp, options) {
this.clp = clp;
this.options = options;
this.isDestroyed = false;
this.buffer = '';
}
async write(chunk) {
if (this.isDestroyed) {
throw new CLPError('Stream has been destroyed', 'VALIDATION_ERROR');
}
this.buffer += chunk;
}
async flush() {
if (this.isDestroyed) {
throw new CLPError('Stream has been destroyed', 'VALIDATION_ERROR');
}
try {
const result = await this.clp.performEncryption(this.buffer, {
withAuthentication: this.options.authentication ?? false,
withCompression: this.options.compression ?? false
});
// Clear buffer after processing
this.buffer = '';
return result;
}
catch (error) {
this.buffer = ''; // Clear on error too
throw error;
}
}
async encrypt(chunk) {
const data = typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk);
return this.clp.performEncryption(data, {
withAuthentication: this.options.authentication ?? false,
withCompression: this.options.compression ?? false
});
}
async decrypt(payload) {
const result = await this.clp.decrypt(payload);
return this.options.encoding === 'binary' ? new TextEncoder().encode(result) : result;
}
close() {
this.destroy();
}
destroy() {
this.buffer = '';
this.isDestroyed = true;
}
}
/**
* Configuration Manager for CLP (Cryptographic Lattice Protocol)
*/
class CLPConfigManager {
/**
* Create configuration from a profile with optional overrides
*/
static create(profile = 'HIGH', overrides = {}) {
const baseConfig = this.PROFILES[profile];
if (!baseConfig) {
throw new CLPError(`Unknown security profile: ${profile}`, 'CONFIG_ERROR');
}
return this.deepMerge(baseConfig, overrides);
}
/**
* Get available security profiles
*/
static getProfiles() {
return Object.keys(this.PROFILES);
}
/**
* Get the default configuration for a profile
*/
static getProfile(profile) {
const config = this.PROFILES[profile];
if (!config) {
throw new CLPError(`Unknown security profile: ${profile}`, 'CONFIG_ERROR');
}
return JSON.parse(JSON.stringify(config));
}
/**
* Validate configuration object
*/
static validate(config) {
const errors = [];
// Security validation
this.validateSecurity(config.security, errors);
// Performance validation
this.validatePerformance(config.performance, errors);
// Feature validation
this.validateFeatures(config.features, errors);
if (errors.length > 0) {
throw new CLPError(`Configuration validation failed: ${errors.join(', ')}`, 'CONFIG_ERROR', { validationErrors: errors });
}
}
static validateSecurity(security, errors) {
if (security.lattice_dimension < 64 || security.lattice_dimension > 2048) {
errors.push('Lattice dimension must be between 64 and 2048');
}
if (security.polynomial_degree < 16 || security.polynomial_degree > 512) {
errors.push('Polynomial degree must be between 16 and 512');
}
if (security.graph_size < 100 || security.graph_size > 10000) {
errors.push('Graph size must be between 100 and 10000');
}
if (security.prime_bits < 128 || security.prime_bits > 1024) {
errors.push('Prime bits must be between 128 and 1024');
}
if (security.key_derivation_rounds < 1000 || security.key_derivation_rounds > 1000000) {
errors.push('Key derivation rounds must be between 1000 and 1000000');
}
if (security.growth_trigger_threshold < 10 || security.growth_trigger_threshold > 1000) {
errors.push('Growth trigger threshold must be between 10 and 1000');
}
}
static validatePerformance(performance, errors) {
if (performance.cache_size < 10 || performance.cache_size > 10000) {
errors.push('Cache size must be between 10 and 10000');
}
if (performance.batch_size < 1 || performance.batch_size > 128) {
errors.push('Batch size must be between 1 and 128');
}
// Check Web Worker availability if enabled
if (performance.use_web_workers && typeof Worker === 'undefined') {
errors.push('Web Workers are not available in this environment');
}
}
static validateFeatures(features, errors) {
// Feature validation logic can be added here
// Currently all feature flags are boolean, so basic type checking is enough
if (typeof features.auto_growth !== 'boolean') {
errors.push('auto_growth must be a boolean');
}
}
/**
* Deep merge two configuration objects
*/
static deepMerge(target, source) {
const result = JSON.parse(JSON.stringify(target));
if (source.security) {
Object.assign(result.security, source.security);
}
if (source.performance) {
Object.assign(result.performance, source.performance);
}
if (source.features) {
Object.assign(result.features, source.features);
}
return result;
}
/**
* Create configuration with security level recommendations
*/
static recommendProfile(requirements) {
const { securityLevel = 'high', performance = 'balanced', environment = 'browser' } = requirements;
// Security-first recommendations
if (securityLevel === 'maximum') {
return 'ULTIMATE';
}
if (securityLevel === 'high') {
return performance === 'fast' ? 'HIGH' : 'ULTIMATE';
}
// Standard security for most use cases
if (environment === 'browser' && performance === 'fast') {
return 'STANDARD';
}
return 'HIGH';
}
}
CLPConfigManager.PROFILES = {
ULTIMATE: {
security: {
lattice_dimension: 1024,
polynomial_degree: 256,
graph_size: 5000,
prime_bits: 512,
key_derivation_rounds: 100000,
growth_trigger_threshold: 50
},
performance: {
enable_parallel_processing: true,
use_web_workers: true,
cache_size: 2000,
batch_size: 32,
compression_enabled: true
},
features: {
auto_growth: true,
authenticated_encryption: true,
streaming_support: true,
debug_mode: false,
strict_validation: true
}
},
HIGH: {
security: {
lattice_dimension: 512,
polynomial_degree: 128,
graph_size: 2000,
prime_bits: 256,
key_derivation_rounds: 50000,
growth_trigger_threshold: 100
},
performance: {
enable_parallel_processing: true,
use_web_workers: false,
cache_size: 1000,
batch_size: 16,
compression_enabled: true
},
features: {
auto_growth: true,
authenticated_encryption: true,
streaming_support: false,
debug_mode: false,
strict_validation: true
}
},
STANDARD: {
security: {
lattice_dimension: 256,
polynomial_degree: 64,
graph_size: 1000,
prime_bits: 256,
key_derivation_rounds: 10000,
growth_trigger_threshold: 200
},
performance: {
enable_parallel_processing: true,
use_web_workers: false,
cache_size: 500,
batch_size: 8,
compression_enabled: false
},
features: {
auto_growth: false,
authenticated_encryption: false,
streaming_support: false,
debug_mode: false,
strict_validation: false
}
}
};
/**
* CLP Utils - Utility functions for CLP operations
*/
class CLPUtils {
/**
* Get system capabilities for environment detection
*/
static getCapabilities() {
return {
webWorkers: typeof Worker !== 'undefined',
standaloneRandom: true,
streams: typeof ReadableStream !== 'undefined',
bigInt: typeof BigInt !== 'undefined',
nodeEnvironment: typeof module !== 'undefined' && typeof module.exports !== 'undefined',
browserEnvironment: typeof window !== 'undefined'
};
}
/**
* Validate configuration with detailed error reporting
*/
static validateConfig(config) {
try {
CLPConfigManager.validate(config);
return { valid: true };
}
catch (error) {
if (error instanceof CLPError) {
return {
valid: false,
error: error.message,
recoveryHints: error.recoveryHints
};
}
return {
valid: false,
error: error.message,
recoveryHints: 'Check the configuration documentation'
};
}
}
/**
* Comprehensive benchmark across all security profiles
*/
static async benchmark(iterations = 10) {
const profiles = ['STANDARD', 'HIGH', 'ULTIMATE'];
const results = {};
for (const profile of profiles) {
console.log(`π Benchmarking ${profile} profile...`);
const config = CLPConfigManager.getProfile(profile);
const clp = new CLPCore(config);
const times = [];
const testMessage = "Benchmark test message for CLP performance evaluation! π";
try {
for (let i = 0; i < iterations; i++) {
const startTime = performance.now ? performance.now() : Date.now();
const encrypted = await clp.encrypt(testMessage).execute();
await clp.decrypt(encrypted);
const endTime = performance.now ? performance.now() : Date.now();
times.push(endTime - startTime);
}
const avgTime = times.reduce((a, b) => a + b, 0) / times.length;
const minTime = Math.min(...times);
const maxTime = Math.max(...times);
const opsPerSec = Math.round(1000 / avgTime);
results[profile] = {
profile,
opsPerSec,
avgTime: `${avgTime.toFixed(2)}ms`,
minTime,
maxTime
};
}
catch (error) {
console.warn(`Benchmark failed for ${profile}:`, error.message);
results[profile] = {
profile,
opsPerSec: 0,
avgTime: 'ERROR',
minTime: 0,
maxTime: 0
};
}
finally {
clp.destroy();
}
}
return {
results,
systemInfo: this.getCapabilities(),
timestamp: Date.now()
};
}
/**
* Comprehensive test suite
*/
static async test(profile = 'HIGH') {
console.log(`π§ͺ Running CLP tests with ${profile} profile...`);
const config = CLPConfigManager.getProfile(profile);
const clp = new CLPCore(config);
const testResults = [];
// Test cases
const tests = [
{ name: 'Basic Encryption/Decryption', test: () => this.testBasicEncryption(clp) },
{ name: 'Empty String Handling', test: () => this.testEmptyString(clp) },
{ name: 'Large Message Handling', test: () => this.testLargeMessage(clp) },
{ name: 'Unicode Support', test: () => this.testUnicodeSupport(clp) },
{ name: 'Authentication Tag', test: () => this.testAuthentication(clp) },
{ name: 'Protocol Evolution', test: () => this.testEvolution(clp) },
{ name: 'Error Handling', test: () => this.testErrorHandling(clp) },
{ name: 'Configuration Validation', test: () => this.testConfigValidation() }
];
let passed = 0;
let failed = 0;
const durations = [];
for (const { name, test } of tests) {
const startTime = Date.now();
try {
await test();
const duration = Date.now() - startTime;
durations.push(duration);
testResults.push({ name, passed: true, duration });
passed++;
}
catch (error) {
const duration = Date.now() - startTime;
durations.push(duration);
testResults.push({
name,
passed: false,
duration,
error: error.message
});
failed++;
}
}
clp.destroy();
const totalDuration = durations.reduce((a, b) => a + b, 0);
return {
passed,
failed,
total: passed + failed,
duration: totalDuration,
details: testResults
};
}
// Individual test methods
static async testBasicEncryption(clp) {
const message = "Hello, CLP! π";
const encrypted = await clp.encrypt(message).execute();
const decrypted = await clp.decrypt(encrypted);
if (decrypted !== message) {
throw new Error(`Decryption mismatch: expected "${message}", got "${decrypted}"`);
}
}
static async testEmptyString(clp) {
const message = "";
const encrypted = await clp.encrypt(message).execute();
const decrypted = await clp.decrypt(encrypted);
if (decrypted !== message) {
throw new Error('Empty string encryption/decryption failed');
}
}
static async testLargeMessage(clp) {
const message = "A".repeat(10000); // 10KB message
const encrypted = await clp.encrypt(message).execute();
const decrypted = await clp.decrypt(encrypted);
if (decrypted !== message) {
throw new Error('Large message encryption/decryption failed');
}
}
static async testUnicodeSupport(clp) {
const message = "Hello δΈη! π ΠΠ΄ΡΠ°Π²ΡΡΠ²ΡΠΉ ΠΌΠΈΡ! Ω
Ψ±ΨΨ¨Ψ§ Ψ¨Ψ§ΩΨΉΨ§ΩΩ
!";
const encrypted = await clp.encrypt(message).execute();
const decrypted = await clp.decrypt(encrypted);
if (decrypted !== message) {
throw new Error('Unicode encryption/decryption failed');
}
}
static async testAuthentication(clp) {
const message = "Authenticated message";
const encrypted = await clp.encrypt(message)
.withAuthentication()
.execute();
if (!encrypted.auth) {
throw new Error('Authentication tag not generated');
}
const decrypted = await clp.decrypt(encrypted);
if (decrypted !== message) {
throw new Error('Authenticated encryption/decryption failed');
}
}
static async testEvolution(clp) {
const info1 = clp.getInfo();
await clp.evolve();
const info2 = clp.getInfo();
if (info2.currentState.growthCycle <= info1.currentState.growthCycle) {
throw new Error('Protocol evolution failed');
}
}
static async testErrorHandling(clp) {
try {
// Test invalid payload
await clp.decrypt({});
throw new Error('Should have thrown validation error');
}
catch (error) {
if (!(error instanceof CLPError) || error.code !== 'VALIDATION_ERROR') {
throw new Error('Expected validation error');
}
}
}
static async testConfigValidation() {
const invalidConfig = {
security: { lattice_dimension: 1 }, // Too small
performance: { cache_size: 1 },
features: { auto_growth: false }
};
const result = CLPUtils.validateConfig(invalidConfig);
if (result.valid) {
throw new Error('Should have failed validation');
}
}
/**
* Generate performance report
*/
static generatePerformanceReport(benchmarkResults) {
const lines = [
'π CLP Performance Report',
'='.repeat(50),
'',
'π₯οΈ System Information:',
`ββ Web Workers: ${benchmarkResults.systemInfo.webWorkers ? 'β
' : 'β'}`,
`ββ BigInt Support: ${benchmarkResults.systemInfo.bigInt ? 'β
' : 'β'}`,
`ββ Streams: ${benchmarkResults.systemInfo.streams ? 'β
' : 'β'}`,
`ββ Environment: ${benchmarkResults.systemInfo.nodeEnvironment ? 'Node.js' : 'Browser'}`,
'',
'β‘ Performance Results:'
];
Object.values(benchmarkResults.results).forEach(result => {
lines.push(`ββ ${result.profile}: ${result.opsPerSec} ops/sec (${result.avgTime})`);
});
lines.push('', `π
Generated: ${new Date(benchmarkResults.timestamp).toLocaleString()}`);
return lines.join('\n');
}
/**
* Memory usage estimation
*/
static estimateMemoryUsage(config) {
const dimension = config.security.lattice_dimension;
const cacheSize = config.performance.cache_size;
// Estimates in bytes
const latticeBytes = dimension * dimension * 8; // Assuming 8 bytes per BigInt
const cacheBytes = cacheSize * 1024; // Assuming 1KB per cache entry
const totalBytes = latticeBytes + cacheBytes;
const formatBytes = (bytes) => {
if (bytes < 1024)
return `${bytes}B`;
if (bytes < 1024 * 1024)
return `${(bytes / 1024).toFixed(1)}KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
};
return {
latticeSize: formatBytes(latticeBytes),
cacheSize: formatBytes(cacheBytes),
totalEstimate: formatBytes(totalBytes)
};
}
}
exports.CLPConfigManager = CLPConfigManager;
exports.CLPCore = CLPCore;
exports.CLPError = CLPError;
exports.CLPErrorHandler = CLPErrorHandler;
exports.CLPMath = CLPMath;
exports.CLPUtils = CLPUtils;
exports.GraphLayer = GraphLayer;
exports.HybridLayer = HybridLayer;
exports.LatticeLayer = LatticeLayer;
exports.PolynomialLayer = PolynomialLayer;
exports.default = CLPCore;
//# sourceMappingURL=index.js.map