@gorbchain-xyz/chaindecode
Version:
GorbchainSDK V1.3+ - Complete Solana development toolkit with advanced cryptography, messaging, and collaboration features. Build secure applications with blockchain, DeFi, and end-to-end encryption.
285 lines (284 loc) • 12 kB
JavaScript
/**
* Crypto Manager - Main interface for all cryptographic operations
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { Keypair } from '@solana/web3.js';
import { EncryptionMethod } from './types.js';
import { encryptPersonal, decryptPersonal, decryptPersonalString, PersonalEncryptionSession } from './personal.js';
import { encryptDirect, decryptDirect, decryptDirectString, SecureChannel } from './direct.js';
import { encryptGroup, decryptGroup } from './group.js';
import { createSignatureGroup, addMemberToSignatureGroup, removeMemberFromSignatureGroup, encryptForSignatureGroup, decryptSignatureGroupData } from './signature-group.js';
import { bytesToString, stringToBytes, isValidPublicKey, signData, verifySignature } from './utils.js';
import { bytesToBase58 as encodeBase58, base58ToBytes as decodeBase58 } from '../utils/base58.js';
/**
* Main crypto manager for the SDK
*/
export class CryptoManager {
constructor(config) {
this.groupCache = new Map();
this.config = Object.assign({ defaultMethod: EncryptionMethod.PERSONAL, keyDerivationIterations: 100000, debug: false }, config);
}
/**
* Encrypt data using the specified method
*/
encrypt(data_1) {
return __awaiter(this, arguments, void 0, function* (data, options = {}) {
const method = options.method || this.config.defaultMethod;
switch (method) {
case EncryptionMethod.PERSONAL:
if (!options.privateKey) {
throw new Error('Private key required for personal encryption');
}
return encryptPersonal(data, options.privateKey, { compress: options.compress });
case EncryptionMethod.DIRECT:
if (!options.privateKey || !options.recipientPublicKey) {
throw new Error('Private key and recipient public key required for direct encryption');
}
return encryptDirect(data, options.recipientPublicKey, options.privateKey, { compress: options.compress });
case EncryptionMethod.GROUP:
if (!options.groupMetadata) {
throw new Error('Group metadata required for group encryption');
}
return encryptGroup(data, options.groupMetadata, { compress: options.compress });
case EncryptionMethod.SIGNATURE_GROUP:
if (!options.groupId || !options.privateKey) {
throw new Error('Group ID and private key required for signature group encryption');
}
const groupMeta = yield this.getGroupMetadata(options.groupId);
if (!groupMeta) {
throw new Error('Group not found');
}
// Get sender's public key
const senderKeypair = Keypair.fromSecretKey(typeof options.privateKey === 'string'
? decodeBase58(options.privateKey)
: options.privateKey);
return encryptForSignatureGroup(data, groupMeta, options.privateKey, senderKeypair.publicKey.toBase58(), { compress: options.compress });
default:
throw new Error(`Unsupported encryption method: ${method}`);
}
});
}
/**
* Decrypt data
*/
decrypt(encryptionResult, privateKey, options) {
return __awaiter(this, void 0, void 0, function* () {
switch (encryptionResult.method) {
case EncryptionMethod.PERSONAL:
return decryptPersonal(encryptionResult, privateKey);
case EncryptionMethod.DIRECT:
return decryptDirect(encryptionResult, privateKey);
case EncryptionMethod.GROUP:
if (!(options === null || options === void 0 ? void 0 : options.publicKey)) {
throw new Error('Public key required for group decryption');
}
return decryptGroup(encryptionResult, privateKey, options.publicKey);
case EncryptionMethod.SIGNATURE_GROUP:
if (!(options === null || options === void 0 ? void 0 : options.publicKey)) {
throw new Error('Public key required for signature group decryption');
}
return decryptSignatureGroupData(encryptionResult, privateKey, options.publicKey, { verifySignature: options.verifySignature });
default:
throw new Error(`Unsupported decryption method: ${encryptionResult.method}`);
}
});
}
/**
* Decrypt data and return as string
*/
decryptString(encryptionResult, privateKey, options) {
return __awaiter(this, void 0, void 0, function* () {
const decrypted = yield this.decrypt(encryptionResult, privateKey, options);
return bytesToString(decrypted);
});
}
/**
* Create a new signature-based group
*/
createSignatureGroup(groupName_1, creatorPrivateKey_1) {
return __awaiter(this, arguments, void 0, function* (groupName, creatorPrivateKey, initialMembers = [], permissions) {
const group = yield createSignatureGroup(groupName, creatorPrivateKey, initialMembers, permissions);
// Cache the group
this.groupCache.set(group.groupId, group);
return group;
});
}
/**
* Add a member to a signature group
*/
addMemberToGroup(groupId, newMember, authorizedMemberPrivateKey, authorizedMemberPublicKey) {
return __awaiter(this, void 0, void 0, function* () {
const group = yield this.getGroupMetadata(groupId);
if (!group) {
throw new Error('Group not found');
}
const updatedGroup = yield addMemberToSignatureGroup(group, newMember, authorizedMemberPrivateKey, authorizedMemberPublicKey);
// Update cache
this.groupCache.set(groupId, updatedGroup);
return updatedGroup;
});
}
/**
* Remove a member from a signature group
*/
removeMemberFromGroup(groupId_1, memberToRemove_1, authorizedMemberPrivateKey_1, authorizedMemberPublicKey_1) {
return __awaiter(this, arguments, void 0, function* (groupId, memberToRemove, authorizedMemberPrivateKey, authorizedMemberPublicKey, rotateKeys = true) {
const group = yield this.getGroupMetadata(groupId);
if (!group) {
throw new Error('Group not found');
}
const updatedGroup = yield removeMemberFromSignatureGroup(group, memberToRemove, authorizedMemberPrivateKey, authorizedMemberPublicKey, rotateKeys);
// Update cache
this.groupCache.set(groupId, updatedGroup);
return updatedGroup;
});
}
/**
* Create a secure channel between two parties
*/
createSecureChannel(localPrivateKey, remotePublicKey) {
return new SecureChannel(localPrivateKey, remotePublicKey);
}
/**
* Create a personal encryption session
*/
createPersonalSession(privateKey) {
return new PersonalEncryptionSession(privateKey);
}
/**
* Sign data
*/
sign(data, privateKey) {
const dataBytes = typeof data === 'string' ? stringToBytes(data) : data;
const privateKeyBytes = typeof privateKey === 'string'
? decodeBase58(privateKey)
: privateKey;
return encodeBase58(signData(dataBytes, privateKeyBytes));
}
/**
* Verify signature
*/
verify(data, signature, publicKey) {
const dataBytes = typeof data === 'string' ? stringToBytes(data) : data;
const signatureBytes = decodeBase58(signature);
const publicKeyBytes = decodeBase58(publicKey);
return verifySignature(dataBytes, signatureBytes, publicKeyBytes);
}
/**
* Get group metadata (from cache or storage)
*/
getGroupMetadata(groupId) {
return __awaiter(this, void 0, void 0, function* () {
return this.groupCache.get(groupId) || null;
});
}
/**
* Store group metadata
*/
storeGroupMetadata(group) {
return __awaiter(this, void 0, void 0, function* () {
this.groupCache.set(group.groupId, group);
});
}
/**
* List all cached groups
*/
listCachedGroups() {
return Array.from(this.groupCache.keys());
}
/**
* Clear group cache
*/
clearGroupCache() {
this.groupCache.clear();
}
/**
* Validate a public key
*/
validatePublicKey(publicKey) {
return isValidPublicKey(publicKey);
}
/**
* Generate a new keypair
*/
generateKeypair() {
const keypair = Keypair.generate();
return {
publicKey: keypair.publicKey.toBase58(),
privateKey: encodeBase58(keypair.secretKey)
};
}
// Direct method aliases for backward compatibility and testing
/**
* Encrypt data using personal encryption
*/
encryptPersonal(data, privateKey, options) {
return __awaiter(this, void 0, void 0, function* () {
return encryptPersonal(data, privateKey, options);
});
}
/**
* Decrypt personal encrypted data
*/
decryptPersonal(encryptionResult, privateKey) {
return __awaiter(this, void 0, void 0, function* () {
return decryptPersonal(encryptionResult, privateKey);
});
}
/**
* Decrypt personal encrypted data and return as string
*/
decryptPersonalString(encryptionResult, privateKey) {
return __awaiter(this, void 0, void 0, function* () {
return decryptPersonalString(encryptionResult, privateKey);
});
}
/**
* Encrypt data for direct communication
*/
encryptDirect(data, recipientPublicKey, senderPrivateKey, options) {
return __awaiter(this, void 0, void 0, function* () {
return encryptDirect(data, recipientPublicKey, senderPrivateKey, options);
});
}
/**
* Decrypt direct encrypted data
*/
decryptDirect(encryptionResult, recipientPrivateKey) {
return __awaiter(this, void 0, void 0, function* () {
return decryptDirect(encryptionResult, recipientPrivateKey);
});
}
/**
* Decrypt direct encrypted data and return as string
*/
decryptDirectString(encryptionResult, recipientPrivateKey) {
return __awaiter(this, void 0, void 0, function* () {
return decryptDirectString(encryptionResult, recipientPrivateKey);
});
}
/**
* Encrypt data for group
*/
encryptGroup(data, groupMetadata, options) {
return __awaiter(this, void 0, void 0, function* () {
return encryptGroup(data, groupMetadata, options);
});
}
/**
* Decrypt group encrypted data
*/
decryptGroup(encryptionResult, privateKey, publicKey) {
return __awaiter(this, void 0, void 0, function* () {
return decryptGroup(encryptionResult, privateKey, publicKey);
});
}
}