Skip to content

kpj2006/ZKmail

Repository files navigation

📧 ZKMail: Decentralized Privacy-Preserving Email Platform on Solana

Zero-Knowledge Proofs + Solana Blockchain for Secure, Private Email Threat Detection

Project: ZKMail - Decentralized Email & Search with Zero-Knowledge Proofs
Blockchain: Solana
License: MIT
Repository: emaiLZKPManagement


📋 Table of Contents

  1. Problem Statement
  2. Solution Architecture
  3. How It Works
  4. Key Features
  5. System Components
  6. Quick Start
  7. 3-Terminal Workflow
  8. Threat Detection Engine
  9. Zero-Knowledge Proof System
  10. Solana Smart Contract Integration
  11. Dashboard
  12. Environment Configuration
  13. Testing
  14. Deployment

Problem Statement

The Centralization Problem (Web2)

In traditional college/corporate email systems:

  • 🚨 Full Surveillance: IT administrators have complete access to all student/corporate emails, metadata, and search history
  • 🚨 No Privacy Boundary: Email content is stored on centralized servers with unrestricted admin access
  • 🚨 Data Misuse Risk: Personal information can be accessed, analyzed, or shared without consent
  • 🚨 Trust Issues: Students have zero control over who can see their private communications

Example: A student searches for "mental health resources" or "LGBTQ+ support" - the IT admin can see this, violating privacy and potentially causing harm.


Solution Architecture

ZKMail: Privacy by Design

┌─────────────────────────────────────────────────────────────────┐
│                    STUDENT CLIENT (Browser/App)                 │
│  - Receives email from Mailchain                               │
│  - Scans message locally for malicious patterns                │
│  - If MALICIOUS → Generate ZKP, send to Solana               │
│  - If BENIGN → Delete locally, zero data sent               │
└─────────────────────────────────────────────────────────────────┘
                              ↓
                        [Local Analysis]
                              ↓
                    ┌─────────┴─────────┐
                    ↓                   ↓
            [MALICIOUS]           [BENIGN]
                    ↓                   ↓
        ┌───────────────────┐   [Delete Locally]
        │  Generate ZKP     │   [Send Nothing]
        │  Proof that:      │   [Privacy = 100%]
        │  - Event Type     │
        │  - Timestamp      │
        │  (NO message body)│
        └─────────┬─────────┘
                  ↓
    ┌─────────────────────────────┐
    │  Submit to Solana Network   │
    │  - ZKP Commitment          │
    │  - Event Type              │
    │  - Student ID (anonymous)  │
    │  - Timestamp               │
    └─────────────┬───────────────┘
                  ↓
    ┌─────────────────────────────┐
    │  Solana Smart Contract      │
    │  - Verify ZKP               │
    │  - Store threat record      │
    │  - Emit event to authorities│
    │  - Maintain immutable log   │
    └─────────────┬───────────────┘
                  ↓
    ┌─────────────────────────────┐
    │  Admin Dashboard            │
    │  - View threats (anonymous) │
    │  - Verify ZKP on blockchain │
    │  - Check transaction history│
    │  - NO access to emails      │
    └─────────────────────────────┘

Key Privacy Guarantee

If email is benign: ✅ Authorities see NOTHING If email is malicious: 👁️ Authorities see ONLY: threat type, severity, timestamp, anonymous ID


How It Works

1. Student Receives Email

Student inbox receives email via Mailchain:
  From: attacker@gmail.com
  Subject: "Verify your account immediately"
  Body: "Click here to verify your credentials..."

1A. Mailchain Message Fetching (New Method)

ZKMail introduces a novel approach to fetch encrypted messages from Mailchain inboxes:

// NEW: Mailchain SDK Integration for inbox access
import { Mailchain } from '@mailchain/sdk';

// Step 1: Initialize Mailchain client with student's recovery phrase
const mailchain = Mailchain.fromSecretRecoveryPhrase(
  'word1 word2 word3 ... word24'  // BIP39 recovery phrase
);

// Step 2: Fetch all messages from student's inbox
// This is not avaible in mailchain docs - uses getMessagesInInboxView() endpoint
const messages = await mailchain._mailboxOperations
  .inboxApi
  .getMessagesInInboxView();
// Returns: Array of encrypted MessagePreviewCrypto objects

// Step 3: Decrypt each message locally on student's device
for (const message of messages) {
  // Decrypt using messagePreviewCrypto (student-side only)
  const decrypted = await mailchain._mailboxOperations
    .messagePreviewCrypto
    .decrypt(message.encryptedBuffer);
  
  // Convert to readable UTF-8 text
  const readableText = Buffer.from(decrypted).toString('utf-8')
    .replace(/[\x00-\x1F]/g, '')  // Remove control characters
    .trim();
  
  // Now ready for threat scanning
  const threatAnalysis = scanForMaliciousPatterns(readableText);
}

2. Local Client-Side Analysis

No data is sent to any server at this point.

// Running in student's browser/app
const emailContent = decryptedMessage;
const threatAnalysis = scanForMaliciousPatterns(emailContent);

if (threatAnalysis.isMalicious) {
  // Generate ZKP (proves threat, reveals nothing else)
  const zkp = generateThreatProof({
    threatType: 'phishing',      // ← Only this
    severity: 'HIGH',             // ← And this
    timestamp: Date.now(),        // ← And this
    // ❌ NO: message body, sender, recipient, keywords
  });
  
  // Send ZKP to Solana (minimal data)
  submitToSolana(zkp);
} else {
  // Benign - nothing sent, message deleted locally
  deleteMessage();
}

3. ZKP Generation

Zero-Knowledge Proof proves malicious activity without revealing content:

// What the student knows (PRIVATE):
const privateData = {
  messageBody: "Click here to verify your credentials...",
  sender: "attacker@gmail.com",
  recipient: "student@example.com",
  keywords: ["verify", "credentials", "click here"]
};

// What we prove (PUBLIC):
const publicProof = {
  threatType: 'PHISHING',
  severity: 'HIGH',
  timestamp: 1698700000,
  commitment: '0x5f8a3b9c...' // SHA256 hash
};

// ZKP: "I know content that has phishing keywords"
// Verifier: "I believe you, but you never showed me the content!"

4. Submit to Solana

Minimal data posted to blockchain:

{
  "zkp": {
    "commitment": "0x5f8a3b9c7d2e1a4f...",
    "signature": "0x2c4d7e1f3a5b6c7d...",
    "verified": true
  },
  "threatMetadata": {
    "threatType": "PHISHING",
    "severity": "HIGH",
    "studentId": "anonymous_xyz",
    "timestamp": 1698700000
  },
  "solanaTransaction": "54uM3NjxZw7DV2QEk...pE4y"
}

5. Admin Dashboard Views Anonymously

Authorities can see threats were detected, but NOT the email content:

┌─────────────────────────────────────────┐
│        ZKMail Admin Dashboard           │
├─────────────────────────────────────────┤
│                                         │
│  🔴 THREATS DETECTED: 127               │
│  ✅ VERIFIED ON BLOCKCHAIN: 127        │
│  👥 AFFECTED STUDENTS: 12 (anonymous)  │
│                                         │
│  Recent Threats:                        │
│  ├─ 🚨 PHISHING (HIGH) - 2 mins ago    │
│  ├─ 🚨 PHISHING (CRITICAL) - 5 mins ago│
│  ├─ 🔺 MALWARE (MEDIUM) - 12 mins ago  │
│  └─ 🔺 SOC.ENG (HIGH) - 18 mins ago    │
│                                         │
│  ✓ View on Solana Blockchain            │
│  ✓ Verify ZKP Proof but can see which   |
|   student affected                      │
│  ✓ Check Transaction History            │
│                                         │
│  ❌ Cannot Access: Email Content        │
│  ❌ Cannot Access: Sender               |
│                                         │
└─────────────────────────────────────────┘

Key Features

✅ Privacy-First Design

  • Client-Side Scanning: Malicious pattern detection happens on student's device
  • Zero Data Leakage: Benign emails = no data sent anywhere
  • Minimal Metadata: Only threat type, severity, timestamp sent to blockchain

✅ Decentralized & Immutable

  • Solana Blockchain: All threat records immutably stored on blockchain
  • No Central Database: No single point of failure or compromise
  • Verifiable Records: Anyone can verify threat proofs on Solana

✅ Authority Transparency

  • Full Audit Trail: All threat submissions recorded on blockchain
  • Cryptographic Verification: ZKP signatures prove threat was real
  • No Access to Content: Technical guarantee of privacy

✅ Threat Detection

  • 37 Threat Keywords across 3 categories:
    • Phishing (17): "verify account", "click here", "urgent action", etc.
    • Malware (8): ".exe", ".dll", "enable macros", etc.
    • Social Engineering (12): "claim prize", "tax refund", "nigerian prince", etc.
  • Severity Levels: LOW, MEDIUM, HIGH, CRITICAL
  • Real-Time Monitoring: 24/7 continuous scanning

System Components

1. Student Client (Frontend)

Location: admin-dashboard1/ (Can be adapted for client use)

Technologies: React + Vite + TypeScript

Responsibilities:

  • Decrypt emails from Mailchain (using BIP39 recovery phrases)
  • Scan message content for threat keywords locally
  • Generate ZKP when threat detected
  • Submit ZKP to Solana smart contract
  • Display local threat notifications

Key Files:

admin-dashboard1/
├── src/
│   ├── App.tsx              # Main dashboard component
│   ├── components/          # Reusable UI components
│   ├── services/
│   │   ├── apiService.ts    # API communication
│   │   ├── zkpService.ts    # ZKP generation [🔄 IN PROGRESS]
│   │   └── solanaService.ts # Solana interaction [🔄 IN PROGRESS]
│   └── config/
│       └── monitored-students.ts  # Student credentials

2. Express API Server

Location: mailchain-send-api/

Technologies: Node.js + Express + TypeScript

Responsibilities:

  • Manage student identities and recovery phrases
  • Coordinate threat detection across 5 students
  • Provide API endpoints for threat queries
  • Validate and verify ZKP proofs
  • Forward threat data to Solana

Key Files:

mailchain-send-api/
├── src/
│   ├── controllers/
│   │   └── mail.controller.ts       # Threat detection logic
│   ├── services/
│   │   ├── mail.service.ts          # Email operations
│   │   ├── monitoringService.ts     # Centralized monitoring
│   │   ├── zkpService.ts            # ZKP generation [🔄]
│   │   └── solanaService.ts         # Blockchain integration
│   ├── routes/
│   │   └── mail.route.ts            # API endpoints
│   └── app.ts
├── test-send-threats.js             # Send test threat emails
└── test-centralized-monitoring.js   # Monitor all students

3. Mailchain Integration

Technology: Mailchain SDK v0.31.0

Functionality:

  • Secure encrypted email communication
  • Private key management (BIP39 recovery phrases)
  • Message encryption/decryption
  • Support for 5 anonymous student accounts

4. Threat Detection Engine

37 Keywords organized in 3 categories:

Phishing (17 keywords):

  • "verify account", "verify your account", "verify credentials"
  • "click here", "click here immediately", "urgent action required"
  • "account suspended", "confirm your identity", "unusual activity"
  • "suspicious activity", "unauthorized access", "confirm password"
  • "reset password immediately", "re-enter password", "validate account"

Malware (8 keywords):

  • "download attachment", "run executable"
  • ".exe", ".dll", "macro enabled"
  • "enable macros", "allow macro", "security risk"

Social Engineering (12 keywords):

  • "claim prize", "won a prize", "congratulations you won"
  • "verify employment", "verify banking", "update banking info"
  • "tax refund", "nigerian prince", "urgent assistance needed"

Severity Calculation:

4+ keywords  → CRITICAL 🔴
3 keywords   → HIGH     🟡
2 keywords   → MEDIUM   🔵
1 keyword    → LOW      🟢

5. Zero-Knowledge Proof System

Status: 🔄 IN PROGRESS

Purpose: Prove threat exists without revealing content

Algorithm: EdDSA (Elliptic Curve Digital Signature)

Components:

  • Commitment: SHA256 hash of (threatType + severity + timestamp)
  • Signature: EdDSA signature proving knowledge of private data
  • Verification: Solana program verifies ZKP on-chain

6. Solana Smart Contract

Purpose: Immutable threat record storage and verification

Functionality:

  • Accept ZKP submissions from students
  • Verify EdDSA signatures
  • Store threat records on-chain
  • Emit events for dashboard
  • Maintain transaction history

Data Structure:

pub struct ThreatRecord {
    pub commitment: [u8; 32],           // ZKP commitment
    pub threat_type: ThreatType,        // PHISHING, MALWARE, SOC_ENG
    pub severity: u8,                   // 1-4 (LOW to CRITICAL)
    pub student_id: [u8; 32],          // Hashed student ID
    pub timestamp: i64,
    pub transaction_id: String,         // Solana TxID
    pub verified: bool,
}

7. Admin Dashboard

Location: admin-dashboard1/

Technologies: React + Vite + TypeScript + Tailwind CSS

Display:

  • Real-time threat statistics
  • Threat severity breakdown
  • Anonymous affected students count
  • Blockchain verification links
  • Transaction history
  • No access to email content

Quick Start

Prerequisites

  • Node.js 16+ and npm installed
  • Solana CLI (optional, for local validator)
  • Windows PowerShell or WSL terminal

Step 1: Generate Student Keypairs

cd client
node dist/bin/generate-student-keypairs.js --count 5 --start 11

Creates 5 students (011-015) with BIP39 recovery phrases.

Step 2: Configure Environment

File: mailchain-send-api/.env.students.local

STUDENT_11_RECOVERY_PHRASE=word1 word2 word3 ... word24
STUDENT_12_RECOVERY_PHRASE=word1 word2 word3 ... word24
STUDENT_13_RECOVERY_PHRASE=word1 word2 word3 ... word24
STUDENT_14_RECOVERY_PHRASE=word1 word2 word3 ... word24
STUDENT_15_RECOVERY_PHRASE=word1 word2 word3 ... word24

File: mailchain-send-api/.env.solana.local (for ZKP/blockchain)

# Solana Configuration
SOLANA_RPC_URL=https://api.devnet.solana.com
SOLANA_COMMITMENT=processed

# Admin Wallet
SOLANA_ADMIN_PRIVATE_KEY=[base58_encoded_keypair]

# ZKP Configuration
ZKP_ALGORITHM=EdDSA
ZKP_VERIFICATION_ENABLED=true

# Smart Contract Program
SOLANA_PROGRAM_ID=YOUR_DEPLOYED_PROGRAM_ID_HERE

Step 3: Install Dependencies

cd mailchain-send-api && npm install
cd ../admin-dashboard1 && npm install
cd ../client && npm install

Step 4: Build Projects

# Backend
cd mailchain-send-api && npm run build

# Frontend
cd ../admin-dashboard1 && npm run build

# Client
cd ../client && npm run build

3-Terminal Workflow

Terminal 1: Start Express API Server (Port 3001)

cd mailchain-send-api
npm run dev

Expected output:

🚀 App listening on the port 3001
✅ Monitoring service initialized
📡 Ready to detect threats

Terminal 2: Send Test Threat Emails

cd mailchain-send-api
node test-send-threats.js

This sends 5 threat emails to students_011 and student_012:

  • 2x Phishing attacks
  • 2x Malware threats
  • 1x Social engineering

Expected output:

✅ Threat 1 sent to student_011@mailchain.com
✅ Threat 2 sent to student_011@mailchain.com
✅ Threat 3 sent to student_012@mailchain.com
✅ Threat 4 sent to student_012@mailchain.com
✅ Threat 5 sent to student_011@mailchain.com

🎉 5 threats sent successfully!

Terminal 3: Monitor and View Threats

cd mailchain-send-api
node test-centralized-monitoring.js

Displays real-time threat monitoring dashboard every 30 seconds:

╔═════════════════════════════════════════════════════════╗
║  CENTRALIZED THREAT MONITORING - REAL-TIME DASHBOARD   ║
╚═════════════════════════════════════════════════════════╝

🔄 Monitoring 5 students every 30 seconds...

📊 SUMMARY:
   Total Threats: 5
   Affected Students: 2
   
   Severity Breakdown:
   ├─ 🔴 CRITICAL: 2
   ├─ 🟡 HIGH: 2
   ├─ 🔵 MEDIUM: 1
   └─ 🟢 LOW: 0

👥 BY STUDENT:
   student_011: 3 threats
   ├─ 🚨 PHISHING (HIGH)
   ├─ 🚨 PHISHING (HIGH)
   └─ 🔺 SOC_ENG (MEDIUM)
   
   student_012: 2 threats
   ├─ 🚨 PHISHING (CRITICAL)
   └─ 🚨 MALWARE (HIGH)

Terminal 4 (Optional): View Admin Dashboard

cd admin-dashboard1
npm run dev

Open browser to http://localhost:5173:

┌─────────────────────────────────┐
│    ZKMail Admin Dashboard       │
├─────────────────────────────────┤
│                                 │
│  Total Threats        5         │
│  Verified on Chain    5 ✓      │
│  Affected Students    2         │
│  Avg Severity         HIGH      │
│                                 │
│  Phishing:     2                │
│  Malware:      1                │
│  Soc.Eng:      2                │
│                                 │
└─────────────────────────────────┘

Threat Detection Engine

Detailed Message Processing Pipeline

Message from Inbox
        │
        ▼
Encrypted Buffer (Mailchain)
        │
        ├─ Decrypt using messagePreviewCrypto.decrypt()
        │  └─ Uses BIP39 recovery phrase + private key
        ▼
Decrypted Buffer
        │
        ├─ Convert to UTF-8 encoding
        ├─ Remove control characters (0x00-0x1F)
        ├─ Clean extra whitespace
        ▼
Readable Text Content
        │
        ├─ Search for 37 threat keywords
        │  ├─ Phishing (17 keywords): "verify account", "click here immediately", "urgent action", etc.
        │  ├─ Malware (8 keywords): ".exe", ".dll", "enable macros", "download attachment", etc.
        │  └─ Social Engineering (12 keywords): "claim prize", "nigerian prince", "tax refund", etc.
        ▼
Keywords Found?
        │
        ├─ NO → Continue to next message
        │        Email is benign ✅
        │        Delete locally, send NOTHING
        │        (100% Privacy preserved)
        │
        └─ YES → Calculate Threat Severity
                 ├─ 4+ keywords = CRITICAL (🔴)
                 ├─ 3 keywords = HIGH (🟡)
                 ├─ 2 keywords = MEDIUM (🔵)
                 └─ 1+ keyword = LOW (🟢)
                 ▼
            Generate ZKP Proof
                 ├─ Private: Email content, sender, keywords
                 ├─ Public: Severity level, threat type, timestamp
                 └─ Result: Commitment hash (proof)
                 ▼
            Submit to Solana
                 ├─ ZKP commitment
                 ├─ Threat metadata (no content)
                 └─ Student anonymous ID
                 ▼
            Authority Dashboard
                 ├─ Sees threat type & severity
                 ├─ Sees blockchain verification link
                 └─ CANNOT see email content

How It Works

Student receives email
         ↓
    Is encrypted? (YES, via Mailchain)
         ↓
  Decrypt using BIP39 recovery phrase
         ↓
    Extract text content
         ↓
  Search for 37 threat keywords
         ↓
    Any keywords found? (NO)
         ↓
    Delete locally, send nothing ✅
         ↓
    (Student privacy: 100%)

---

    Student receives email
         ↓
    Is encrypted? (YES, via Mailchain)
         ↓
  Decrypt using BIP39 recovery phrase
         ↓
    Extract text content
         ↓
  Search for 37 threat keywords
         ↓
    Any keywords found? (YES - 3 keywords)
         ↓
    Severity = HIGH (3 keywords)
         ↓
  Generate ZKP proof
    - Proves: "Malicious email detected"
    - Hides: Email content, sender, recipient
         ↓
  Submit ZKP + metadata to Solana
    - threatType: PHISHING
    - severity: HIGH
    - timestamp: 1698700000
    - studentId: hash(anonymous)
         ↓
  Admin sees: "PHISHING threat detected (severity: HIGH)"
             "Verify on blockchain: https://explorer.solana.com/tx/..."
         ↓
  Admin CANNOT see: Email content, who sent it, specific keywords

Zero-Knowledge Proof System

What is a ZKP?

A cryptographic proof that a statement is true without revealing the underlying data.

Example:

  • Statement: "This email contains malicious keywords"
  • Proof: Cryptographic commitment that proves the statement
  • Verifier sees: Proof is valid ✅
  • Verifier does NOT see: What keywords, email content, sender

Implementation: EdDSA Signatures

// On student's device (PRIVATE)
const emailContent = decryptedMessage; // "Click here to verify account..."

// Generate proof components
const proofData = {
  threatType: 'PHISHING',
  severity: 'HIGH',
  timestamp: Date.now()
};

// Create commitment (public)
const commitment = SHA256(JSON.stringify(proofData));
// Result: 0x5f8a3b9c7d2e1a4f...

// Sign with private key (proves knowledge)
const signature = EdDSA.sign(commitment, privateKey);
// Result: 0x2c4d7e1f3a5b6c7d...

// Submit to Solana
const zkp = {
  commitment: '0x5f8a3b9c...',
  signature: '0x2c4d7e1f...',
  publicKey: '0x1a2b3c4d...',
  verified: true,
  algorithm: 'EdDSA'
};

Proof Structure

{
  // Zero-Knowledge Proof
  zkp: {
    commitment: "0x5f8a3b9c7d2e1a4f...",    // SHA256 hash
    signature: "0x2c4d7e1f3a5b6c7d...",    // EdDSA signature
    publicKey: "0x1a2b3c4d5e6f7g8h...",    // Public key for verification
    verified: true,                          // Verified by Solana program
    algorithm: "EdDSA"
  },
  
  // Threat Metadata (minimal)
  threat: {
    threatType: "PHISHING",
    severity: "HIGH",
    studentId: "hash_xyz123",                // Anonymous
    timestamp: 1698700000
  },
  
  // Blockchain Link
  solanaTxId: "54uM3NjxZw7DV2QEk...pE4y",
  blockExplorerUrl: "https://explorer.solana.com/tx/54uM3N...pE4y?cluster=devnet"
}

Verification Process

On Solana Blockchain:

// Solana program verifies ZKP
fn verify_threat_proof(proof: &ThreatProof) -> Result<bool> {
  // 1. Hash threat metadata
  let commitment = hash(&proof.threat_metadata);
  
  // 2. Verify EdDSA signature
  let is_valid = ed25519_verify(
    &proof.signature,
    &commitment,
    &proof.public_key
  );
  
  // 3. Store threat record if valid
  if is_valid {
    store_threat_record(&proof);
    emit_threat_event(&proof);
    return Ok(true);
  }
  
  return Ok(false);
}

Solana Smart Contract Integration

Contract Overview

Location: programs/zk-mail-auditor/ (Anchor program)

Purpose: Verify ZKPs and store immutable threat records on-chain

Deployed to: Solana Devnet (test network)

Threat Submission Flow

┌──────────────────┐
│  Student Client  │
│  Generates ZKP   │
└────────┬─────────┘
         ↓
    ┌────────────────────────────────┐
    │  1. Create Transaction         │
    │  - Include ZKP commitment      │
    │  - Include threat metadata     │
    │  - Sign with student keypair   │
    └────────┬───────────────────────┘
             ↓
    ┌────────────────────────────────┐
    │  2. Submit to Solana Network   │
    │  - RPC Endpoint: devnet        │
    │  - Program: Smart Contract     │
    └────────┬───────────────────────┘
             ↓
    ┌────────────────────────────────┐
    │  3. Solana Program Processes   │
    │  - Verify EdDSA signature      │
    │  - Validate threat data        │
    │  - Store record on-chain       │
    │  - Emit ThreatDetected event   │
    └────────┬───────────────────────┘
             ↓
    ┌────────────────────────────────┐
    │  4. Admin Dashboard Receives   │
    │  - Threat event notification   │
    │  - Solana TxID for verification│
    │  - Can verify ZKP on-chain     │
    └────────────────────────────────┘

On-Chain Data Structure

#[account]
pub struct ThreatRecord {
  pub bump: u8,
  pub commitment: [u8; 32],           // ZKP commitment (hash)
  pub threat_type: u8,                // 1=PHISHING, 2=MALWARE, 3=SOC_ENG
  pub severity: u8,                   // 1=LOW, 2=MEDIUM, 3=HIGH, 4=CRITICAL
  pub student_id: [u8; 32],          // SHA256(student_public_key)
  pub timestamp: i64,
  pub submitter: Pubkey,              // Student's wallet
  pub verified: bool,
  pub transaction_id: String,
}

#[account]
pub struct ThreatLog {
  pub bump: u8,
  pub total_threats: u64,
  pub critical_threats: u64,
  pub high_threats: u64,
  pub medium_threats: u64,
  pub low_threats: u64,
  pub last_updated: i64,
}

Smart Contract Methods

// Submit threat proof
pub fn submit_threat_proof(
  ctx: Context<SubmitThreat>,
  commitment: [u8; 32],
  signature: [u8; 64],
  public_key: [u8; 32],
  threat_data: ThreatData,
) -> Result<()>

// Verify threat proof
pub fn verify_threat(
  ctx: Context<VerifyThreat>,
  threat_id: Pubkey,
) -> Result<bool>

// Query threats by type
pub fn get_threats_by_type(
  threat_type: u8,
) -> Result<Vec<ThreatRecord>>

// Get threat statistics
pub fn get_statistics() -> Result<ThreatLog>

Example Solana Transaction

{
  "signature": "54uM3NjxZw7DV2QEkp6RHSmJP1C6JAG...pE4y",
  "blockTime": 1698700000,
  "slot": 230000000,
  "transaction": {
    "message": {
      "accountKeys": [
        "student_011_wallet",
        "threat_records_pda",
        "threat_log_pda",
        "system_program"
      ],
      "instructions": [
        {
          "program": "zk-mail-auditor",
          "data": {
            "commitment": "0x5f8a3b9c...",
            "signature": "0x2c4d7e1f...",
            "threatType": "PHISHING",
            "severity": "HIGH",
            "timestamp": 1698700000
          }
        }
      ]
    }
  },
  "meta": {
    "err": null,
    "status": "Ok",
    "fee": 5000,
    "logs": [
      "Program zk-mail-auditor invoked",
      "Threat proof verified ✓",
      "Threat record stored ✓",
      "Event: ThreatDetected emitted"
    ]
  }
}

Dashboard

Admin View

URL: http://localhost:5173

Features:

Real-Time Statistics

┌──────────────────────┬──────────────────────┐
│  Total Threats: 127  │  Verified: 127 ✓    │
└──────────────────────┴──────────────────────┘

┌──────────────────────┬──────────────────────┐
│  Affected Students: 12 (anonymous)         │
└──────────────────────┴──────────────────────┘

┌─────────────┬─────────────┬─────────────┐
│  Critical   │  High       │  Medium     │
│  🔴 34      │  🟡 52      │  🔵 35      │
└─────────────┴─────────────┴─────────────┘

Threat Type Breakdown

Phishing:           75 (59%)
Malware:            32 (25%)
Social Engineering: 20 (16%)

Recent Threats List

[CRITICAL] PHISHING
  Time: Oct 30, 10:23 AM
  Student: (anonymous)
  Verify: https://explorer.solana.com/tx/54uM3N...

[HIGH] MALWARE
  Time: Oct 30, 10:18 AM
  Student: (anonymous)
  Verify: https://explorer.solana.com/tx/7xK9pL...

[HIGH] PHISHING
  Time: Oct 30, 10:15 AM
  Student: (anonymous)
  Verify: https://explorer.solana.com/tx/3mW2jN...

Blockchain Verification

✓ Can verify all ZKP proofs on Solana
✓ View transaction history
✓ Check submission timestamps
✓ Confirm threat authenticity

❌ Cannot see email content
❌ Cannot identify students
❌ Cannot access search history

Environment Configuration

Student Recovery Phrases

File: mailchain-send-api/.env.students.local

# BIP39 24-word recovery phrases for 5 students
STUDENT_11_RECOVERY_PHRASE=abandon ability able about above absent absorb abstract abuse access accident account achieve acid acid acknowledge
STUDENT_12_RECOVERY_PHRASE=acid acidic acidify acids acme acquire across act action activate active actor acts actual acuate ad
STUDENT_13_RECOVERY_PHRASE=ad adapt add adder addiction address adjust adopt adult advance advent advertise advice aerobic affairs afford
STUDENT_14_RECOVERY_PHRASE=afraid after again age agent agree ahead aide aim air airline airport aisle alabama alarm album
STUDENT_15_RECOVERY_PHRASE=alarm album alert alike alive allow almost alone alpha already also alter always am amateur amazing

Note: These are example phrases. Generate secure phrases with:

node client/dist/bin/generate-student-keypairs.js --count 5 --start 11

Solana Configuration

File: mailchain-send-api/.env.solana.local

# Network
SOLANA_RPC_URL=https://api.devnet.solana.com
SOLANA_COMMITMENT=processed
SOLANA_NETWORK=devnet

# Admin Wallet (for deploying contracts and posting threats)
SOLANA_ADMIN_PRIVATE_KEY=[base58_encoded_keypair]
SOLANA_ADMIN_PUBLIC_KEY=[public_key]

# ZKP Configuration
ZKP_ALGORITHM=EdDSA
ZKP_VERIFICATION_ENABLED=true
ZKP_SIGNING_KEY=[private_key_for_signing]

# Smart Contract Program
SOLANA_PROGRAM_ID=YOUR_DEPLOYED_PROGRAM_ID_HERE

# For Local Testing (optional)
SOLANA_LOCAL_VALIDATOR=false
SOLANA_LOCAL_RPC=http://127.0.0.1:8899

API Configuration

File: mailchain-send-api/.env.development.local

# Server
NODE_ENV=development
PORT=3001
LOG_LEVEL=debug

# Mailchain
MAILCHAIN_RPC_URL=https://mailchain.com

# CORS
CORS_ORIGIN=http://localhost:5173

# Rate Limiting
RATE_LIMIT_WINDOW=15
RATE_LIMIT_MAX_REQUESTS=100

Testing

Run Full Test Suite

Terminal 1: Start API Server

cd mailchain-send-api
npm run dev

Terminal 2: Send Test Threats

cd mailchain-send-api
node test-send-threats.js

Terminal 3: Monitor Threats

cd mailchain-send-api
node test-centralized-monitoring.js

Terminal 4: View Dashboard

cd admin-dashboard1
npm run dev
# Open http://localhost:5173

Expected Test Results

✅ Threat Detection: 5 threats detected (2 phishing, 2 malware, 1 soc eng)
✅ Severity Calculation: Correct levels (2 CRITICAL, 2 HIGH, 1 MEDIUM)
✅ Student Isolation: Threats properly attributed to student_011 and student_012
✅ API Responses: All endpoints returning correct data
✅ Dashboard: Real-time updates showing all threats
✅ ZKP Generation: Commitments and signatures valid
✅ Solana Integration: TxIDs returned for each submission

Individual Test Files

# Fetch raw decrypted messages from Mailchain
node test-fetch-richard-inbox.js

# Test message decryption
node test-decrypt-full.js

# Test threat detection on specific email
node test-threat-detection.js

# End-to-end flow test
node test-end-to-end.js

License

MIT - See LICENSE file

About

https://youtu.be/VFoWcNIByE4

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors