DEV Community

Cover image for Healing Hands: Breaking Mental Health Stigma with Zero-Knowledge Privacy
Abhi nandan
Abhi nandan

Posted on

Healing Hands: Breaking Mental Health Stigma with Zero-Knowledge Privacy

Midnight Network Challenge: Protect That Data

This is a submission for the Midnight Network "Privacy First" Challenge - Protect That Data prompt

What I Built

Healing Hands is a privacy-first mental health support platform that enables completely anonymous peer support while maintaining security and preventing abuse. Built for Midnight Network's "Privacy First" Challenge, it solves the critical problem of mental health stigma by allowing users to seek support without fear of identity exposure or discrimination.

Core Problems Solved:

  1. Mental Health Stigma: Users can participate in support groups without revealing their identity
  2. Privacy Concerns: All personal data stays encrypted and anonymous
  3. Trust Issues: Zero-knowledge proofs verify eligibility without exposing medical information
  4. Abuse Prevention: Rate limiting nullifiers prevent spam while maintaining anonymity
  5. Professional Consequences: Healthcare workers, executives, and others can seek help without career risks

Key Features:

  1. Anonymous Identity System: Cryptographic pseudonyms (e.g., "BraveBear958") for persistent participation
  2. Zero-Knowledge Condition Verification: Prove mental health conditions without revealing personal details
  3. Privacy-Preserving Group Matching: Algorithm matches users based on encrypted preferences
  4. End-to-End Encrypted Communications: All messages protected with Signal Protocol
  5. Comprehensive Privacy Dashboard: Real-time monitoring of privacy protections
  6. Advanced Account Management: Secure identity reset, deletion, and key management

Demo

GitHub Repository: Healing Hands - Anonymous Mental Health Support

Demo Video: https://youtu.be/mLV06E3rafY

Demo: https://mindfulsanctuary.netlify.app/ (Mock Data)

How I Used Midnight's Technology

  1. Compact Language Integration
// circuits/mental_health_matching.compact
circuit MentalHealthMatching {
    // Zero-knowledge proof for condition verification
    public input condition_hash: Field;
    private input medical_record: Field;
    private input user_salt: Field;

    // Verify condition without revealing details
    constraint condition_hash == hash(medical_record, user_salt);
}

// circuits/identity_verification.compact  
circuit IdentityVerification {
    // Anonymous identity generation
    public input anonymous_id: Field;
    private input private_key: Field;
    private input identity_salt: Field;

    constraint anonymous_id == hash(private_key, identity_salt);
}
Enter fullscreen mode Exit fullscreen mode
  1. Midnight SDK Implementation
// src/lib/midnight/useMidnight.ts
import { MidnightProvider, generateProof } from '@midnight-ntwrk/sdk'

export const useMidnight = () => {
  const generateAnonymousIdentity = async (userData: any) => {
    // Generate ZK proof for anonymous identity
    const proof = await generateProof('identity_verification', {
      privateKey: userData.privateKey,
      identitySalt: userData.salt
    })

    return {
      anonymousId: proof.publicOutputs.anonymous_id,
      proof: proof.proof
    }
  }

  const verifyCondition = async (condition: string, evidence: any) => {
    // Generate ZK proof for mental health condition
    const proof = await generateProof('mental_health_matching', {
      medicalRecord: evidence.hash,
      userSalt: evidence.salt
    })

    return proof
  }

  return { generateAnonymousIdentity, verifyCondition }
}
Enter fullscreen mode Exit fullscreen mode
  1. Rate Limiting Nullifiers (RLN)
// src/lib/midnight/rln.ts
export class RLNSystem {
  async generateMessageProof(message: string, userSecret: string) {
    // Generate RLN proof to prevent spam
    const nullifier = hash(userSecret, getCurrentEpoch())
    const proof = await generateProof('rln_circuit', {
      message: message,
      secret: userSecret,
      nullifier: nullifier
    })

    return { proof, nullifier }
  }

  async verifyMessageProof(proof: any, nullifier: string) {
    // Verify message is within rate limits
    return await verifyProof('rln_circuit', proof) && 
           !this.isNullifierUsed(nullifier)
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Privacy Metrics Integration
// src/lib/midnight/privacyMetrics.ts
export const getPrivacyMetrics = async () => {
  const metrics = await MidnightProvider.getNetworkStats()

  return {
    zkProofsGenerated: metrics.totalProofs,
    anonymitySetSize: metrics.activeUsers,
    privacyScore: calculatePrivacyScore(metrics),
    circuitHealth: await checkCircuitStatus()
  }
}
Enter fullscreen mode Exit fullscreen mode

Data Protection as a Core Feature

Privacy and data protection are not superficial additions but the foundational architecture of Healing Hands:

  1. Zero-Knowledge Architecture
  • No Personal Data Storage: Platform never sees real names, medical records, or personal information
  • Cryptographic Verification: ZK circuits prove eligibility without data exposure
  • Anonymous Persistence: Users maintain consistent identity without revealing who they are
  1. End-to-End Encryption Stack
// src/lib/encryption/signalProtocol.ts
export class SignalProtocolImplementation {
  // Double Ratchet Algorithm for perfect forward secrecy
  async encryptMessage(message: string, recipientKey: string) {
    const ephemeralKey = generateEphemeralKey()
    const sharedSecret = deriveSharedSecret(ephemeralKey, recipientKey)
    return encrypt(message, sharedSecret)
  }

  // X3DH key agreement for initial setup
  async establishSession(identityKey: string, preKey: string) {
    return performX3DHKeyAgreement(identityKey, preKey)
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Privacy-Preserving Matching Algorithm
// src/lib/matching/privacyPreservingMatcher.ts
export const matchUsers = async (userPreferences: EncryptedPreferences) => {
  // Homomorphic encryption for private set intersection
  const encryptedMatches = await computePrivateIntersection(
    userPreferences.supportTypes,
    availableGroups.map(g => g.encryptedCriteria)
  )

  return decryptMatches(encryptedMatches, userPreferences.privateKey)
}
Enter fullscreen mode Exit fullscreen mode
  1. Comprehensive Privacy Monitoring
  • Real-time Privacy Metrics: Live dashboard showing system health
  • Transparency Reports: Detailed privacy statistics and compliance information
  • User Privacy Controls: Granular control over data sharing and anonymity levels
  1. Secure Account Management
// src/lib/midnight/anonymousAuth.ts
export class AnonymousAuthSystem {
  async deleteAccount(anonymousId: string, passphrase: string) {
    // Secure deletion with ZK circuit data clearing
    const privateKey = await this.decryptPrivateKey(encryptedKey, passphrase)
    if (!privateKey) throw new Error('Invalid passphrase')

    // Clear all associated ZK circuit data
    this.clearZKCircuitData(anonymousId)
    this.clearRLNNullifiers(anonymousId)

    return true
  }
}
Enter fullscreen mode Exit fullscreen mode

Set Up Instructions / Tutorial

Prerequisites
Node.js 18+ and npm
Midnight Network SDK
Git

  1. Clone and Install
git clone https://github.com/yourusername/healing-hands.git
cd healing-hands
npm install
Enter fullscreen mode Exit fullscreen mode
  1. Install Midnight Dependencies
npm install @midnight-ntwrk/sdk @midnight-ntwrk/compact-compiler
Enter fullscreen mode Exit fullscreen mode
  1. Compile ZK Circuits
# Compile Compact circuits
npx compact-compiler circuits/mental_health_matching.compact
npx compact-compiler circuits/identity_verification.compact
npx compact-compiler circuits/membership_rln.compact

# Output will be in compiled/ directory
Enter fullscreen mode Exit fullscreen mode
  1. Environment Setup
# Create .env file
cp .env.example .env

# Configure environment variables
MIDNIGHT_NETWORK_URL=https://testnet.midnight.network
CIRCUIT_PATH=./compiled
PRIVACY_LEVEL=maximum
Enter fullscreen mode Exit fullscreen mode
  1. Initialize Midnight Provider
// src/lib/midnight/provider.ts
import { MidnightProvider } from '@midnight-ntwrk/sdk'

export const initializeMidnight = async () => {
  const provider = new MidnightProvider({
    networkUrl: process.env.MIDNIGHT_NETWORK_URL,
    circuitPath: process.env.CIRCUIT_PATH
  })

  await provider.connect()
  return provider
}
Enter fullscreen mode Exit fullscreen mode
  1. Run Development Server
npm run dev
# Application will be available at http://localhost:5173
Enter fullscreen mode Exit fullscreen mode
  1. Build for Production
npm run build
npm run preview
Enter fullscreen mode Exit fullscreen mode
  1. Deploy to Midnight Network
# Deploy circuits to Midnight Network
npx midnight-deploy --circuits ./compiled --network testnet

# Deploy frontend
npm run build
# Deploy dist/ to your hosting provider
Enter fullscreen mode Exit fullscreen mode

Key Files Structure:

healing-hands/
├── circuits/                    # Compact ZK circuits
│   ├── mental_health_matching.compact
│   ├── identity_verification.compact
│   └── membership_rln.compact
├── src/
│   ├── lib/midnight/           # Midnight SDK integration
│   │   ├── useMidnight.ts
│   │   ├── zkProof.ts
│   │   └── anonymousAuth.ts
│   ├── pages/                  # React components
│   │   ├── ConditionVerification.tsx
│   │   ├── PrivacyStatistics.tsx
│   │   └── AccountManagement.tsx
│   └── components/
├── compiled/                   # Compiled circuits
└── package.json
Enter fullscreen mode Exit fullscreen mode

Testing the Privacy Features:

  1. Create Anonymous Account: Complete onboarding with passphrase
  2. Verify Condition: Use ZK proof to verify mental health condition
  3. Join Support Group: Experience anonymous matching algorithm
  4. Test Privacy Dashboard: Monitor real-time privacy metrics
  5. Account Management: Try identity reset and key management

This implementation demonstrates how Midnight Network's privacy-first technology can solve real-world problems in mental healthcare, providing a secure, anonymous platform for those who need support but fear stigma or professional consequences.

Top comments (2)

Collapse
 
minhlong2605 profile image
Long Phan

great idea!

Collapse
 
abhinandan-r profile image
Abhi nandan

Thanks