@hsuite/dkg-types - Distributed Key Generation Type Definitions

🔐 Comprehensive TypeScript type definitions for Distributed Key Generation with threshold cryptography and Shamir's Secret Sharing

Enterprise-grade type definitions and interfaces providing a complete distributed key generation (DKG) system with threshold cryptography, secure share distribution, member coordination, and protocol message handling for cryptographic operations.


📚 Table of Contents


✨ Quick Start

Installation

npm install @hsuite/dkg-types

Basic Setup

import { IDKG, DKG } from '@hsuite/dkg-types';

// Interface-based type definitions
const clusterStatus: IDKG.NetworkClusterStatus = IDKG.NetworkClusterStatus.BUILDING;

const node: IDKG.INode = {
  operator: '0x123abc...',
  id: 'node-123',
  sn_id: 'smartnode-456',
  vvec: ['vvec1', 'vvec2']
};

// Model-based runtime validation
const shamirShare = new DKG.ShamirSecretShare();
const cluster = new DKG.Cluster();
const member = new DKG.Member();

NestJS Integration

import { DKG } from '@hsuite/dkg-types';

@Controller('dkg')
export class DKGController {
  @Post('cluster')
  @ApiResponse({ type: DKG.Cluster })
  async createCluster(@Body() data: any): Promise<DKG.Cluster> {
    return new DKG.Cluster(data);
  }
}

🏗️ Architecture

Core Component Areas

🔐 Threshold Cryptography

  • Shamir's Secret Sharing - Secure secret splitting with threshold reconstruction

  • Share Distribution - Safe distribution of cryptographic shares among participants

  • Secret Reconstruction - Threshold-based secret recovery from distributed shares

  • Verification Vectors - Cryptographic proof for share validity and integrity

🌐 Network Coordination

  • Cluster Management - Coordinated group operations and state synchronization

  • Node Participation - Individual participant management and communication

  • Member Coordination - Protocol state management and share coordination

  • Status Lifecycle - Complete cluster state transitions from building to ready

📡 Protocol Communication

  • Payload Management - Structured message formats for DKG protocol communication

  • State Synchronization - Consistent state management across network participants

  • Message Validation - Type-safe protocol message handling and verification

  • Secure Channels - Protected communication between DKG participants

🛡️ Security Features

  • Share Integrity - Cryptographic validation of distributed shares

  • Member Authentication - Participant identity verification and management

  • Secure Distribution - Protected share distribution mechanisms

  • Threshold Security - Configurable security thresholds for key reconstruction

Dual Namespace System

🔧 IDKG Namespace (Interfaces)

  • Type Definitions - Pure TypeScript interfaces for cryptographic operations

  • Protocol Structures - DKG protocol message and state interfaces

  • Network Interfaces - Cluster and node management interfaces

  • Cryptographic Types - Threshold cryptography and secret sharing interfaces

🏛️ DKG Namespace (Models)

  • Runtime Validation - Concrete classes with built-in cryptographic validation

  • Swagger Integration - Complete API documentation decorators

  • Protocol Implementation - Concrete DKG protocol implementations

  • Secure Operations - Validated cryptographic operations and state management

Module Structure

src/
├── index.ts                           # Main exports and documentation
├── interfaces/                        # IDKG namespace
│   ├── dkg.namespace.ts               # Central interface hub
│   ├── interfaces/                    # Core interfaces
│   │   ├── dkg.cluster.interface.ts   # Cluster management
│   │   ├── dkg.member.interface.ts    # Member operations
│   │   ├── dkg.node.interface.ts      # Node participation
│   │   └── dkg.*.interface.ts         # Additional interfaces
│   └── namespaces/                    # Specialized domains
│       └── payloads/                  # Protocol message definitions
└── models/                            # DKG namespace
    ├── dkg.namespace.ts               # Central model hub
    ├── models/                        # Core implementations
    │   ├── dkg.cluster.model.ts       # Cluster coordination
    │   ├── dkg.member.model.ts        # Member state management
    │   ├── dkg.node.model.ts          # Node implementation
    │   └── dkg.*.model.ts             # Additional models
    └── namespaces/                    # Domain implementations
        └── payloads/                  # Protocol message implementations

🔧 API Reference

Core Interface Types

Network Status Types

IDKG.NetworkClusterStatus

enum NetworkClusterStatus {
  BUILDING = 'building',              // Initial setup and configuration phase
  ROTATING = 'rotating',              // Members are being added or removed
  BANNING = 'banning',               // Problematic members being removed
  CONTRIBUTIONS_READY = 'contributions_ready', // Ready to accept contributions
  READY = 'ready'                    // Fully operational and processing
}

Cryptographic Types

IDKG.IShamirSecretShare

  • Purpose: Shamir's Secret Sharing scheme implementation interface

  • Features: Secret splitting, threshold reconstruction, share validation

  • Usage: Secure secret distribution among DKG participants

IDKG.IMemberShare

  • Purpose: Individual member share management interface

  • Properties: Share identification, ownership tracking, validation

  • Usage: Share distribution and lifecycle management

Network Participant Types

IDKG.INode

  • Purpose: DKG network participant interface

  • Properties: operator, id, sn_id, vvec

  • Usage: Node identification and verification vector management

IDKG.IMember

  • Purpose: DKG protocol member interface

  • Properties: dkgId, membersShares, verificationVector, secretKeyShare

  • Usage: Member state and cryptographic operations

IDKG.ICluster

  • Purpose: DKG cluster coordination interface

  • Properties: networkId, members, memberships, groupsVvec, threshold

  • Usage: Group operations and threshold management

Status Transition Matrix

Current Status
Allowed Transitions
Description

BUILDING

CONTRIBUTIONS_READY, BANNING

Initial setup completion

CONTRIBUTIONS_READY

READY, ROTATING, BANNING

Accept contributions

READY

ROTATING, BANNING

Normal operations

ROTATING

READY, BANNING

Member changes

BANNING

BUILDING, READY

Member removal

Threshold Configuration

Participants
Recommended Threshold
Security Level
Use Case

3-5

2

Basic

Development/Testing

5-10

3-4

Standard

Production Systems

10-20

5-7

High

Enterprise Networks

20+

8+

Maximum

Critical Infrastructure


📖 Guides

DKG Protocol Implementation Guide

Complete guide to implementing distributed key generation protocols. This covers the full DKG workflow from cluster initialization through key generation, including participant coordination, contribution handling, verification vector management, and threshold cryptography implementation.

Threshold Cryptography Guide

Learn Shamir's Secret Sharing and threshold-based cryptographic operations. This includes secret splitting algorithms, share distribution mechanisms, threshold reconstruction techniques, verification vector creation, and cryptographic proof generation for secure multi-party computations.

Network Coordination Guide

Set up cluster management and participant coordination. This covers cluster state management, member lifecycle handling, network topology configuration, communication protocol implementation, and distributed consensus mechanisms for DKG operations.

Security Best Practices Guide

Implement secure DKG operations and protect against attacks. This includes participant authentication, share integrity verification, secure communication channels, malicious actor detection, byzantine fault tolerance, and cryptographic security best practices.


🎯 Examples

Basic DKG Cluster Setup

import { IDKG, DKG } from '@hsuite/dkg-types';

@Injectable()
export class DKGClusterService {
  
  async createDKGCluster(clusterData: any) {
    try {
      // Create cluster configuration
      const cluster = new DKG.Cluster({
        networkId: clusterData.networkId,
        members: [],
        memberships: [],
        groupsVvec: [],
        threshold: clusterData.threshold || 3
      });

      // Initialize cluster status
      cluster.status = IDKG.NetworkClusterStatus.BUILDING;

      return {
        success: true,
        clusterId: cluster.networkId,
        status: cluster.status,
        threshold: cluster.threshold,
        maxMembers: clusterData.maxMembers || 10,
        createdAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`DKG cluster creation failed: ${error.message}`);
    }
  }

  async addNodeToCluster(clusterId: string, nodeData: any) {
    try {
      // Create node instance
      const node = new DKG.Node({
        operator: nodeData.operatorAddress,
        id: nodeData.nodeId,
        sn_id: nodeData.smartNodeId,
        vvec: [] // Will be populated during DKG process
      });

      // Validate node credentials
      const isValidNode = await this.validateNodeCredentials(node);
      
      if (!isValidNode) {
        throw new Error('Invalid node credentials');
      }

      // Add node to cluster
      const cluster = await this.getCluster(clusterId);
      
      if (cluster.status !== IDKG.NetworkClusterStatus.BUILDING) {
        throw new Error(`Cannot add nodes to cluster in ${cluster.status} status`);
      }

      cluster.members.push(node.id);
      
      return {
        success: true,
        nodeId: node.id,
        clusterId: clusterId,
        totalNodes: cluster.members.length,
        status: 'added'
      };
    } catch (error) {
      throw new Error(`Node addition failed: ${error.message}`);
    }
  }

  async transitionClusterStatus(clusterId: string, targetStatus: IDKG.NetworkClusterStatus) {
    try {
      const cluster = await this.getCluster(clusterId);
      const currentStatus = cluster.status;

      // Validate status transition
      const allowedTransitions = this.getAllowedTransitions(currentStatus);
      
      if (!allowedTransitions.includes(targetStatus)) {
        throw new Error(`Invalid transition from ${currentStatus} to ${targetStatus}`);
      }

      // Perform transition validation
      await this.validateTransition(cluster, targetStatus);

      // Update cluster status
      cluster.status = targetStatus;

      return {
        success: true,
        clusterId,
        previousStatus: currentStatus,
        newStatus: targetStatus,
        transitionedAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Status transition failed: ${error.message}`);
    }
  }

  private getAllowedTransitions(status: IDKG.NetworkClusterStatus): IDKG.NetworkClusterStatus[] {
    const transitions = {
      [IDKG.NetworkClusterStatus.BUILDING]: [
        IDKG.NetworkClusterStatus.CONTRIBUTIONS_READY,
        IDKG.NetworkClusterStatus.BANNING
      ],
      [IDKG.NetworkClusterStatus.CONTRIBUTIONS_READY]: [
        IDKG.NetworkClusterStatus.READY,
        IDKG.NetworkClusterStatus.ROTATING,
        IDKG.NetworkClusterStatus.BANNING
      ],
      [IDKG.NetworkClusterStatus.READY]: [
        IDKG.NetworkClusterStatus.ROTATING,
        IDKG.NetworkClusterStatus.BANNING
      ],
      [IDKG.NetworkClusterStatus.ROTATING]: [
        IDKG.NetworkClusterStatus.READY,
        IDKG.NetworkClusterStatus.BANNING
      ],
      [IDKG.NetworkClusterStatus.BANNING]: [
        IDKG.NetworkClusterStatus.BUILDING,
        IDKG.NetworkClusterStatus.READY
      ]
    };

    return transitions[status] || [];
  }

  private async validateNodeCredentials(node: DKG.Node): Promise<boolean> {
    // Implementation for validating node credentials
    return node.operator && node.id && node.sn_id;
  }

  private async validateTransition(cluster: any, targetStatus: IDKG.NetworkClusterStatus): Promise<void> {
    switch (targetStatus) {
      case IDKG.NetworkClusterStatus.CONTRIBUTIONS_READY:
        if (cluster.members.length < cluster.threshold) {
          throw new Error('Insufficient members for contributions phase');
        }
        break;
      case IDKG.NetworkClusterStatus.READY:
        if (!cluster.groupsVvec || cluster.groupsVvec.length === 0) {
          throw new Error('Group verification vectors not ready');
        }
        break;
    }
  }

  private async getCluster(clusterId: string): Promise<any> {
    // Mock implementation - replace with actual cluster retrieval
    return {
      networkId: clusterId,
      members: [],
      status: IDKG.NetworkClusterStatus.BUILDING,
      threshold: 3,
      groupsVvec: []
    };
  }
}

Shamir's Secret Sharing Implementation

import { IDKG, DKG } from '@hsuite/dkg-types';

@Injectable()
export class ShamirSecretSharingService {
  
  async generateSecretShares(secretData: any) {
    try {
      const totalShares = secretData.totalParticipants;
      const threshold = secretData.threshold;
      const secret = secretData.secret;

      // Validate parameters
      if (threshold > totalShares) {
        throw new Error('Threshold cannot exceed total shares');
      }

      if (threshold < 2) {
        throw new Error('Threshold must be at least 2');
      }

      // Generate shares using Shamir's scheme
      const shares = [];
      
      for (let i = 1; i <= totalShares; i++) {
        const shamirShare = new DKG.ShamirSecretShare({
          shareIndex: i,
          shareValue: this.calculateShare(secret, i, threshold),
          threshold: threshold,
          totalShares: totalShares
        });

        shares.push(shamirShare);
      }

      return {
        success: true,
        totalShares: shares.length,
        threshold: threshold,
        shares: shares.map(share => ({
          index: share.shareIndex,
          value: share.shareValue, // In production, this would be encrypted
          id: `share-${share.shareIndex}`
        })),
        generatedAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Secret share generation failed: ${error.message}`);
    }
  }

  async reconstructSecret(shareData: any[]) {
    try {
      const shares = shareData.map(data => new DKG.ShamirSecretShare(data));
      
      // Validate sufficient shares
      const threshold = shares[0]?.threshold;
      
      if (shares.length < threshold) {
        throw new Error(`Insufficient shares: need ${threshold}, got ${shares.length}`);
      }

      // Validate share compatibility
      const isCompatible = this.validateShareCompatibility(shares);
      
      if (!isCompatible) {
        throw new Error('Shares are not compatible for reconstruction');
      }

      // Reconstruct secret using Lagrange interpolation
      const reconstructedSecret = this.lagrangeInterpolation(shares);

      return {
        success: true,
        secret: reconstructedSecret,
        sharesUsed: shares.length,
        threshold: threshold,
        reconstructedAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Secret reconstruction failed: ${error.message}`);
    }
  }

  async distributeShares(clusterId: string, shares: any[]) {
    try {
      const cluster = await this.getCluster(clusterId);
      const members = await this.getClusterMembers(clusterId);

      if (shares.length !== members.length) {
        throw new Error('Share count must match member count');
      }

      const distributions = [];

      for (let i = 0; i < members.length; i++) {
        const member = members[i];
        const share = shares[i];

        // Create member share record
        const memberShare = new DKG.MemberShare({
          memberId: member.id,
          shareData: share,
          distributedAt: Date.now(),
          verified: false
        });

        // Distribute share to member
        await this.distributeShareToMember(member, memberShare);

        distributions.push({
          memberId: member.id,
          shareIndex: share.shareIndex,
          distributed: true
        });
      }

      return {
        success: true,
        clusterId,
        totalDistributions: distributions.length,
        distributions,
        distributedAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Share distribution failed: ${error.message}`);
    }
  }

  async verifyShareIntegrity(shareData: any, verificationVector: string[]) {
    try {
      const share = new DKG.ShamirSecretShare(shareData);

      // Verify share against verification vector
      const isValid = this.verifyShareAgainstVector(share, verificationVector);

      if (!isValid) {
        throw new Error('Share verification failed');
      }

      return {
        success: true,
        shareId: share.shareIndex,
        verified: true,
        verificationVector: verificationVector.length,
        verifiedAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Share verification failed: ${error.message}`);
    }
  }

  private calculateShare(secret: string, index: number, threshold: number): string {
    // Mock implementation - replace with actual Shamir's calculation
    // In production, use proper finite field arithmetic
    return `share-${secret}-${index}-${threshold}`;
  }

  private validateShareCompatibility(shares: DKG.ShamirSecretShare[]): boolean {
    if (shares.length === 0) return false;

    const firstShare = shares[0];
    return shares.every(share => 
      share.threshold === firstShare.threshold &&
      share.totalShares === firstShare.totalShares
    );
  }

  private lagrangeInterpolation(shares: DKG.ShamirSecretShare[]): string {
    // Mock implementation - replace with actual Lagrange interpolation
    // In production, implement proper polynomial interpolation
    return `reconstructed-secret-from-${shares.length}-shares`;
  }

  private verifyShareAgainstVector(share: DKG.ShamirSecretShare, vector: string[]): boolean {
    // Mock implementation - replace with actual verification
    return vector.length > 0 && share.shareIndex > 0;
  }

  private async getCluster(clusterId: string): Promise<any> {
    // Mock implementation
    return { networkId: clusterId };
  }

  private async getClusterMembers(clusterId: string): Promise<any[]> {
    // Mock implementation
    return [
      { id: 'member-1' },
      { id: 'member-2' },
      { id: 'member-3' }
    ];
  }

  private async distributeShareToMember(member: any, share: DKG.MemberShare): Promise<void> {
    // Implementation for secure share distribution
  }
}

Member Coordination and State Management

import { IDKG, DKG } from '@hsuite/dkg-types';

@Injectable()
export class DKGMemberService {
  
  async createMember(memberData: any) {
    try {
      // Create DKG member
      const member = new DKG.Member({
        dkgId: memberData.dkgId,
        membersShares: [],
        verificationVector: [],
        receivedShares: [],
        secretKeyShare: '',
        secretKeyShamir: [],
        shamirSecretShares: []
      });

      return {
        success: true,
        memberId: member.dkgId,
        status: 'initialized',
        sharesReceived: member.receivedShares.length,
        verificationVector: member.verificationVector.length,
        createdAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Member creation failed: ${error.message}`);
    }
  }

  async coordinateContributions(clusterId: string) {
    try {
      const cluster = await this.getCluster(clusterId);
      const members = await this.getClusterMembers(clusterId);

      // Validate cluster is ready for contributions
      if (cluster.status !== IDKG.NetworkClusterStatus.CONTRIBUTIONS_READY) {
        throw new Error(`Cluster not ready for contributions: ${cluster.status}`);
      }

      const contributions = [];

      for (const memberData of members) {
        const member = new DKG.Member(memberData);

        // Generate member's contribution
        const contribution = await this.generateMemberContribution(member, cluster);

        // Broadcast contribution to other members
        await this.broadcastContribution(clusterId, member.dkgId, contribution);

        contributions.push({
          memberId: member.dkgId,
          contributionSize: contribution.verificationVector.length,
          broadcast: true
        });
      }

      return {
        success: true,
        clusterId,
        totalContributions: contributions.length,
        contributions,
        coordinatedAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Contribution coordination failed: ${error.message}`);
    }
  }

  async processReceivedShare(memberId: string, shareData: any) {
    try {
      const member = await this.getMember(memberId);
      
      // Create member share
      const memberShare = new DKG.MemberShare({
        senderId: shareData.senderId,
        shareValue: shareData.shareValue,
        shareIndex: shareData.shareIndex,
        verified: false
      });

      // Verify share integrity
      const isValidShare = await this.verifyReceivedShare(memberShare, member.verificationVector);
      
      if (!isValidShare) {
        throw new Error('Share verification failed');
      }

      // Add to member's received shares
      member.receivedShares.push(memberShare);
      memberShare.verified = true;

      // Check if all shares received
      const allSharesReceived = await this.checkAllSharesReceived(member);

      return {
        success: true,
        memberId,
        shareFrom: shareData.senderId,
        totalReceived: member.receivedShares.length,
        allReceived: allSharesReceived,
        verified: memberShare.verified,
        processedAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Share processing failed: ${error.message}`);
    }
  }

  async generateSecretKey(memberId: string) {
    try {
      const member = await this.getMember(memberId);

      // Validate all shares received
      const allSharesReceived = await this.checkAllSharesReceived(member);
      
      if (!allSharesReceived) {
        throw new Error('Cannot generate secret key: missing shares');
      }

      // Combine received shares to generate secret key
      const secretKeyShare = this.combineShares(member.receivedShares);
      
      // Update member with secret key
      member.secretKeyShare = secretKeyShare;

      // Generate Shamir secret shares for this member
      const shamirShares = await this.generateShamirShares(member, secretKeyShare);
      member.secretKeyShamir = shamirShares;

      return {
        success: true,
        memberId,
        secretKeyGenerated: true,
        shamirSharesGenerated: shamirShares.length,
        keyGeneratedAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Secret key generation failed: ${error.message}`);
    }
  }

  async validateMemberState(memberId: string) {
    try {
      const member = await this.getMember(memberId);

      const validation = {
        memberId,
        hasVerificationVector: member.verificationVector.length > 0,
        sharesReceived: member.receivedShares.length,
        sharesVerified: member.receivedShares.filter(share => share.verified).length,
        hasSecretKey: !!member.secretKeyShare,
        shamirSharesGenerated: member.secretKeyShamir.length,
        isComplete: false
      };

      // Check if member setup is complete
      validation.isComplete = (
        validation.hasVerificationVector &&
        validation.sharesReceived > 0 &&
        validation.sharesReceived === validation.sharesVerified &&
        validation.hasSecretKey &&
        validation.shamirSharesGenerated > 0
      );

      return {
        success: true,
        validation,
        validatedAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Member validation failed: ${error.message}`);
    }
  }

  private async generateMemberContribution(member: DKG.Member, cluster: any): Promise<any> {
    // Generate verification vector and shares for other members
    const verificationVector = this.generateVerificationVector(cluster.threshold);
    const shares = this.generateSharesForMembers(cluster.members, cluster.threshold);

    member.verificationVector = verificationVector;

    return {
      memberId: member.dkgId,
      verificationVector,
      shares
    };
  }

  private async broadcastContribution(clusterId: string, memberId: string, contribution: any): Promise<void> {
    // Implementation for broadcasting contributions to cluster members
  }

  private async verifyReceivedShare(share: DKG.MemberShare, verificationVector: string[]): Promise<boolean> {
    // Implementation for verifying received shares against verification vector
    return verificationVector.length > 0 && share.shareValue;
  }

  private async checkAllSharesReceived(member: DKG.Member): Promise<boolean> {
    // Implementation for checking if all expected shares are received
    const expectedShares = await this.getExpectedShareCount(member.dkgId);
    return member.receivedShares.length >= expectedShares;
  }

  private combineShares(shares: any[]): string {
    // Implementation for combining shares into secret key
    return `combined-secret-key-from-${shares.length}-shares`;
  }

  private async generateShamirShares(member: DKG.Member, secretKey: string): Promise<string[]> {
    // Implementation for generating Shamir shares from secret key
    return [`shamir-1-${secretKey}`, `shamir-2-${secretKey}`];
  }

  private generateVerificationVector(threshold: number): string[] {
    // Mock implementation for verification vector generation
    return Array.from({ length: threshold }, (_, i) => `vvec-${i + 1}`);
  }

  private generateSharesForMembers(members: string[], threshold: number): any[] {
    // Mock implementation for generating shares for other members
    return members.map((memberId, index) => ({
      memberId,
      shareIndex: index + 1,
      shareValue: `share-value-${index + 1}`
    }));
  }

  private async getMember(memberId: string): Promise<DKG.Member> {
    // Mock implementation - replace with actual member retrieval
    return new DKG.Member({
      dkgId: memberId,
      membersShares: [],
      verificationVector: [],
      receivedShares: [],
      secretKeyShare: '',
      secretKeyShamir: [],
      shamirSecretShares: []
    });
  }

  private async getExpectedShareCount(memberId: string): Promise<number> {
    // Mock implementation
    return 3;
  }

  private async getCluster(clusterId: string): Promise<any> {
    // Mock implementation
    return {
      networkId: clusterId,
      status: IDKG.NetworkClusterStatus.CONTRIBUTIONS_READY,
      threshold: 3,
      members: ['member-1', 'member-2', 'member-3']
    };
  }

  private async getClusterMembers(clusterId: string): Promise<any[]> {
    // Mock implementation
    return [
      { dkgId: 'member-1' },
      { dkgId: 'member-2' },
      { dkgId: 'member-3' }
    ];
  }
}

Protocol Message Handling

import { IDKG, DKG } from '@hsuite/dkg-types';

@Injectable()
export class DKGProtocolService {
  
  async handleProtocolMessage(messageData: any) {
    try {
      // Create payload from message
      const payload = new DKG.Payload.Message({
        type: messageData.type,
        senderId: messageData.senderId,
        recipientId: messageData.recipientId,
        data: messageData.data,
        timestamp: Date.now()
      });

      // Route message based on type
      const result = await this.routeMessage(payload);

      return {
        success: true,
        messageId: payload.timestamp,
        type: payload.type,
        processed: true,
        result,
        processedAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Protocol message handling failed: ${error.message}`);
    }
  }

  async broadcastToCluster(clusterId: string, messageData: any) {
    try {
      const cluster = await this.getCluster(clusterId);
      const members = cluster.members;

      const broadcasts = [];

      for (const memberId of members) {
        const payload = new DKG.Payload.Broadcast({
          type: 'cluster_broadcast',
          clusterId: clusterId,
          recipientId: memberId,
          data: messageData,
          timestamp: Date.now()
        });

        // Send to member
        await this.sendPayloadToMember(memberId, payload);

        broadcasts.push({
          memberId,
          messageType: payload.type,
          sent: true
        });
      }

      return {
        success: true,
        clusterId,
        totalBroadcasts: broadcasts.length,
        broadcasts,
        broadcastAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Cluster broadcast failed: ${error.message}`);
    }
  }

  async validateProtocolState(clusterId: string) {
    try {
      const cluster = await this.getCluster(clusterId);
      const members = await this.getClusterMembers(clusterId);

      const validation = {
        clusterId,
        clusterStatus: cluster.status,
        totalMembers: members.length,
        threshold: cluster.threshold,
        memberStates: [],
        protocolComplete: false,
        issues: []
      };

      // Validate each member state
      for (const member of members) {
        const memberValidation = await this.validateMemberProtocolState(member);
        validation.memberStates.push(memberValidation);

        if (!memberValidation.isValid) {
          validation.issues.push(`Member ${member.dkgId}: ${memberValidation.issues.join(', ')}`);
        }
      }

      // Check overall protocol completion
      const validMembers = validation.memberStates.filter(state => state.isValid).length;
      validation.protocolComplete = (
        validMembers >= cluster.threshold &&
        cluster.status === IDKG.NetworkClusterStatus.READY
      );

      return {
        success: true,
        validation,
        validatedAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Protocol state validation failed: ${error.message}`);
    }
  }

  private async routeMessage(payload: any): Promise<any> {
    switch (payload.type) {
      case 'share_distribution':
        return await this.handleShareDistribution(payload);
      case 'verification_vector':
        return await this.handleVerificationVector(payload);
      case 'contribution':
        return await this.handleContribution(payload);
      case 'key_generation':
        return await this.handleKeyGeneration(payload);
      default:
        throw new Error(`Unknown message type: ${payload.type}`);
    }
  }

  private async handleShareDistribution(payload: any): Promise<any> {
    // Implementation for share distribution messages
    return {
      type: 'share_distribution',
      processed: true,
      recipientId: payload.recipientId
    };
  }

  private async handleVerificationVector(payload: any): Promise<any> {
    // Implementation for verification vector messages
    return {
      type: 'verification_vector',
      processed: true,
      vectorSize: payload.data.vector?.length || 0
    };
  }

  private async handleContribution(payload: any): Promise<any> {
    // Implementation for contribution messages
    return {
      type: 'contribution',
      processed: true,
      contributorId: payload.senderId
    };
  }

  private async handleKeyGeneration(payload: any): Promise<any> {
    // Implementation for key generation messages
    return {
      type: 'key_generation',
      processed: true,
      keyGenerated: true
    };
  }

  private async validateMemberProtocolState(member: any): Promise<any> {
    const issues = [];
    
    if (!member.verificationVector || member.verificationVector.length === 0) {
      issues.push('Missing verification vector');
    }

    if (!member.receivedShares || member.receivedShares.length === 0) {
      issues.push('No shares received');
    }

    if (!member.secretKeyShare) {
      issues.push('Secret key not generated');
    }

    return {
      memberId: member.dkgId,
      isValid: issues.length === 0,
      issues
    };
  }

  private async sendPayloadToMember(memberId: string, payload: any): Promise<void> {
    // Implementation for sending payload to specific member
  }

  private async getCluster(clusterId: string): Promise<any> {
    // Mock implementation
    return {
      networkId: clusterId,
      status: IDKG.NetworkClusterStatus.READY,
      members: ['member-1', 'member-2', 'member-3'],
      threshold: 2
    };
  }

  private async getClusterMembers(clusterId: string): Promise<any[]> {
    // Mock implementation
    return [
      {
        dkgId: 'member-1',
        verificationVector: ['vv1', 'vv2'],
        receivedShares: [{ verified: true }],
        secretKeyShare: 'sk1'
      },
      {
        dkgId: 'member-2',
        verificationVector: ['vv3', 'vv4'],
        receivedShares: [{ verified: true }],
        secretKeyShare: 'sk2'
      }
    ];
  }
}

🔗 Integration

Required Dependencies

{
  "@nestjs/common": "^10.4.2",
  "@nestjs/core": "^10.4.2",
  "@hsuite/nestjs-swagger": "^1.0.3",
  "@compodoc/compodoc": "^1.1.23"
}

Module Integration

import { Module } from '@nestjs/common';
import { DKG, IDKG } from '@hsuite/dkg-types';

@Module({
  providers: [
    DKGClusterService,
    ShamirSecretSharingService,
    DKGMemberService,
    DKGProtocolService
  ],
  exports: [
    DKGClusterService,
    ShamirSecretSharingService,
    DKGMemberService,
    DKGProtocolService
  ]
})
export class DKGTypesModule {}

Documentation Generation

# Generate comprehensive documentation
npm run compodoc

# Generate documentation with coverage report
npm run compodoc:coverage

Integration with HSuite Ecosystem

// Complete integration with other HSuite modules
import { DKG, IDKG } from '@hsuite/dkg-types';
import { AuthModule } from '@hsuite/auth';
import { SmartNetworkModule } from '@hsuite/smart-network';
import { HashgraphModule } from '@hsuite/hashgraph';

@Module({
  imports: [
    AuthModule,
    SmartNetworkModule,
    HashgraphModule
  ]
})
export class DKGEcosystemModule {}

@Injectable()
export class IntegratedDKGService {
  constructor(
    private authService: AuthService,
    private networkService: SmartNetworkService,
    private hashgraphService: HashgraphService
  ) {}

  async createSecureDKGCluster(
    clusterData: any,
    session: IAuth.ICredentials.IWeb3.IEntity
  ): Promise<DKG.Cluster> {
    // 1. Validate permissions
    const hasPermission = await this.authService.validatePermission(
      session,
      'dkg:cluster:create'
    );

    if (!hasPermission) {
      throw new Error('Insufficient permissions for DKG cluster creation');
    }

    // 2. Validate network membership
    const networkMember = await this.networkService.validateMember(session.walletId);
    
    if (!networkMember.isActive) {
      throw new Error('Must be active network member to create DKG cluster');
    }

    // 3. Create DKG cluster
    const cluster = new DKG.Cluster({
      networkId: clusterData.networkId,
      members: [],
      memberships: [],
      groupsVvec: [],
      threshold: clusterData.threshold
    });

    // 4. Register on blockchain
    const txResponse = await this.hashgraphService.registerDKGCluster(cluster);
    
    // 5. Update with blockchain data
    cluster.networkId = txResponse.clusterId;
    cluster.status = IDKG.NetworkClusterStatus.BUILDING;

    return cluster;
  }
}

Use Cases

🔐 Distributed Key Management

  • Multi-party key generation without single points of failure

  • Threshold-based secret reconstruction for enhanced security

  • Secure share distribution among trusted participants

  • Cryptographic proof and verification systems

🏢 Enterprise Security Infrastructure

  • Multi-signature wallet implementations

  • Distributed certificate authorities

  • Secure multi-party computation protocols

  • Enterprise-grade cryptographic operations

🌐 Blockchain Network Security

  • Validator key generation for consensus networks

  • Distributed custody solutions for digital assets

  • Cross-chain bridge security mechanisms

  • Network governance key management

High-Availability Systems

  • Fault-tolerant cryptographic operations

  • Disaster recovery key reconstruction

  • Geographic distribution of key shares

  • Scalable threshold cryptography implementations


🔐 Enterprise Cryptography: Comprehensive TypeScript definitions for distributed key generation with threshold cryptography and Shamir's Secret Sharing.

🛡️ Security-First Design: Complete security validation, share integrity verification, and cryptographic proof systems.

🌐 Network Coordination: Advanced cluster management, member coordination, and protocol state synchronization.


Built with ❤️ by the HbarSuite Team Copyright © 2024 HbarSuite. All rights reserved.

Last updated