Skip to content

VirusHacks/HackSync-3.0

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🏰 FORTRESS - Secure Web3 Transaction Platform

FORTRESS Banner

A security-first blockchain application with End-to-End Encryption, Role-Based Access Control, ML-Powered Anomaly Detection, and Immutable Audit Trails

Solidity React Node.js Ethereum


📋 Table of Contents


🎯 Overview

FORTRESS is a secure Web3 transaction platform built with enterprise-grade security features. It enables users to send cryptocurrency transactions with military-grade encryption while providing administrators with real-time fraud detection and immutable audit trails.

Core Principles

  • Security First: Every feature is designed with security as the primary concern
  • Zero Trust: Never trust, always verify - all actions are authenticated and authorized
  • Defense in Depth: Multiple layers of security controls
  • Transparency: All actions are logged and auditable

🔐 Key Security Features

Feature Description Implementation
E2EE End-to-End Encryption for transaction messages AES-256-GCM + ECDH
RBAC Role-Based Access Control On-chain OpenZeppelin AccessControl
Fraud Detection ML-powered anomaly detection Off-chain analysis + On-chain enforcement
Audit Trail Immutable logging with Merkle proofs Hybrid on-chain/off-chain

🔒 End-to-End Encryption (E2EE)

FORTRESS implements true end-to-end encryption ensuring that sensitive transaction data can only be read by the sender and recipient.

How It Works

┌─────────────────────────────────────────────────────────────────────┐
│                        ENCRYPTION FLOW                               │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  SENDER                                                   RECIPIENT  │
│  ┌──────────┐                                           ┌──────────┐│
│  │ Private  │ ──── ECDH Key Exchange ────────────────▶ │ Public   ││
│  │ Key      │                                           │ Key      ││
│  └──────────┘                                           └──────────┘│
│       │                                                       │     │
│       ▼                                                       ▼     │
│  ┌──────────────────┐                              ┌──────────────┐ │
│  │ Shared Secret    │                              │ Shared Secret│ │
│  │ (Computed)       │                              │ (Computed)   │ │
│  └──────────────────┘                              └──────────────┘ │
│       │                                                       │     │
│       ▼                                                       ▼     │
│  ┌──────────────────┐     Blockchain Storage      ┌──────────────┐ │
│  │ AES-256-GCM      │ ──▶ [Encrypted Payload] ──▶ │ AES-256-GCM  │ │
│  │ Encrypt          │                              │ Decrypt      │ │
│  └──────────────────┘                              └──────────────┘ │
│                                                                      │
└─────────────────────────────────────────────────────────────────────┘

Cryptographic Specifications

Component Algorithm Key Size
Symmetric Encryption AES-256-GCM 256 bits
Key Exchange ECDH (secp256k1) 256 bits
Key Derivation HKDF-SHA256 256 bits
Integrity GCM Auth Tag 128 bits

What Gets Encrypted

Field Encrypted Reason
Message ✅ Yes Sensitive user content
Keyword ✅ Yes May reveal transaction intent
Amount ❌ No Required for blockchain transfer
Addresses ❌ No Required for routing
Timestamp ❌ No Set by smart contract

Key Management

// Keys are generated client-side and never leave the browser
const keyPair = await generateECDHKeyPair();

// Private key stored ONLY in session storage
sessionStorage.setItem('fortress_private_key', privateKey);

// Public key can be shared for receiving encrypted messages
registerPublicKey(walletAddress, publicKey);

Security Guarantees

  • ✅ Backend cannot read encrypted data
  • ✅ Administrators cannot decrypt messages
  • ✅ Each transaction uses a unique symmetric key
  • ✅ Forward secrecy with ephemeral keys
  • ✅ Integrity verification via GCM auth tags

🛡️ Role-Based Access Control (RBAC)

FORTRESS implements on-chain Role-Based Access Control using OpenZeppelin's AccessControl, ensuring that permissions are enforced by the blockchain itself.

Role Hierarchy

┌─────────────────────────────────────────────────────────────────────┐
│                         ROLE HIERARCHY                               │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│                    ┌──────────────────────┐                         │
│                    │  DEFAULT_ADMIN_ROLE  │                         │
│                    │  (Contract Deployer) │                         │
│                    └──────────┬───────────┘                         │
│                               │                                      │
│              ┌────────────────┼────────────────┐                    │
│              │                │                │                    │
│              ▼                ▼                ▼                    │
│    ┌─────────────────┐ ┌─────────────┐ ┌─────────────────┐         │
│    │   ADMIN_ROLE    │ │ AUDITOR_ROLE│ │   USER_ROLE     │         │
│    │                 │ │             │ │                 │         │
│    │ • Freeze accts  │ │ • View logs │ │ • Send txns     │         │
│    │ • Flag txns     │ │ • Verify    │ │ • View own txns │         │
│    │ • Manage roles  │ │ • Audit     │ │ • Encrypt msgs  │         │
│    └─────────────────┘ └─────────────┘ └─────────────────┘         │
│                                                                      │
└─────────────────────────────────────────────────────────────────────┘

Role Permissions Matrix

Action USER ADMIN AUDITOR DEFAULT_ADMIN
Send Transactions
View Own Transactions
View All Transactions
Flag Transactions
Freeze Accounts
View Audit Logs 📊
Verify Audit Integrity
Assign Roles

Smart Contract Implementation

// FortressRBAC.sol
contract FortressRBAC is AccessControl {
    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
    bytes32 public constant AUDITOR_ROLE = keccak256("AUDITOR_ROLE");
    bytes32 public constant USER_ROLE = keccak256("USER_ROLE");
    
    mapping(address => bool) public frozenAccounts;
    
    modifier onlyAdmin() {
        require(hasRole(ADMIN_ROLE, msg.sender), "Requires ADMIN_ROLE");
        _;
    }
    
    modifier notFrozen(address account) {
        require(!frozenAccounts[account], "Account is frozen");
        _;
    }
    
    function freezeAccount(address account, string calldata reason) 
        external 
        onlyAdmin 
    {
        frozenAccounts[account] = true;
        emit AccountFrozen(account, msg.sender, reason);
    }
}

Authentication Flow

┌──────────┐      ┌──────────┐      ┌──────────┐      ┌──────────┐
│  Client  │      │  Server  │      │ Metamask │      │Blockchain│
└────┬─────┘      └────┬─────┘      └────┬─────┘      └────┬─────┘
     │                 │                 │                 │
     │  1. Request     │                 │                 │
     │     Nonce       │                 │                 │
     │────────────────▶│                 │                 │
     │                 │                 │                 │
     │  2. Return      │                 │                 │
     │     Nonce+Msg   │                 │                 │
     │◀────────────────│                 │                 │
     │                 │                 │                 │
     │  3. Sign Message│                 │                 │
     │────────────────────────────────▶  │                 │
     │                 │                 │                 │
     │  4. Signature   │                 │                 │
     │◀────────────────────────────────  │                 │
     │                 │                 │                 │
     │  5. Verify Sig  │                 │                 │
     │────────────────▶│                 │                 │
     │                 │  6. Get Roles   │                 │
     │                 │────────────────────────────────▶  │
     │                 │                 │                 │
     │                 │  7. Roles       │                 │
     │                 │◀────────────────────────────────  │
     │                 │                 │                 │
     │  8. JWT Token   │                 │                 │
     │◀────────────────│                 │                 │
     │                 │                 │                 │

🔍 Anomaly & Fraud Detection

FORTRESS implements a sophisticated ML-powered fraud detection system that analyzes transactions in real-time and takes automated enforcement actions.

Detection Architecture

┌─────────────────────────────────────────────────────────────────────┐
│                    FRAUD DETECTION PIPELINE                          │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  ┌────────────┐    ┌──────────────────┐    ┌───────────────────┐   │
│  │Transaction │───▶│  Off-Chain       │───▶│  On-Chain         │   │
│  │ Submitted  │    │  Detection Engine│    │  Enforcement      │   │
│  └────────────┘    └──────────────────┘    └───────────────────┘   │
│                           │                        │                │
│                           ▼                        ▼                │
│                    ┌──────────────┐         ┌─────────────┐        │
│                    │ ML Models    │         │ Actions:    │        │
│                    │ • Isolation  │         │ • ALLOW     │        │
│                    │   Forest     │         │ • FLAG      │        │
│                    │ • Autoencoder│         │ • FREEZE    │        │
│                    │ • Neural Net │         │ • BLOCK     │        │
│                    └──────────────┘         └─────────────┘        │
│                                                                      │
└─────────────────────────────────────────────────────────────────────┘

Detection Triggers

Trigger Description Threshold Weight
Large Amount Transaction exceeds user's average 3x average 30 pts
Velocity Too many transactions per minute 5/min 25 pts
New Address High value to unknown recipient >1 ETH 20 pts
Rapid Succession Multiple transactions in short time <60s apart 15 pts
Unusual Time Transaction at odd hours 1-5 AM UTC 10 pts

Anomaly Scoring System

// Scoring thresholds
const CONFIG = {
  anomalyScoreThreshold: 70,   // Score >= 70 = Anomalous
  autoFreezeThreshold: 90,     // Score >= 90 = Auto-freeze
};

// Scoring formula
anomalyScore = 
  (largeAmount ? 30 : 0) +
  (velocityViolation ? 25 : 0) +
  (newAddressHighValue ? 20 : 0) +
  (rapidSuccession ? 15 : 0) +
  (unusualTime ? 10 : 0);

// Actions
if (anomalyScore >= 90)  FREEZE_ACCOUNT
else if (anomalyScore >= 70)  FLAG_TRANSACTION
else  ALLOW

Visual Indicators in Admin Dashboard

Score Range Status Color Icon
0-49 Normal 🟢 Green ✓ Shield
50-69 Suspicious 🟡 Yellow ⚠ Warning
70-89 Anomalous 🟠 Orange 🛡️ Alert
90-100 Critical 🔴 Red ⛔ Stop

Enforcement Flow

┌─────────────────────────────────────────────────────────────────────┐
│                      ENFORCEMENT ACTIONS                             │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  Detection Result                    On-Chain Action                 │
│  ─────────────────                   ───────────────                 │
│                                                                      │
│  Score < 70                          ALLOW                           │
│  (Normal)                            └─▶ Transaction proceeds        │
│                                                                      │
│  Score 70-89                         FLAG_TRANSACTION                │
│  (Anomalous)                         └─▶ Marked for admin review     │
│                                       └─▶ Transaction proceeds       │
│                                       └─▶ Alert logged               │
│                                                                      │
│  Score >= 90                         FREEZE_ACCOUNT                  │
│  (Critical)                          └─▶ Account frozen on-chain     │
│                                       └─▶ All future txns blocked    │
│                                       └─▶ Admin notified             │
│                                       └─▶ Audit entry created        │
│                                                                      │
└─────────────────────────────────────────────────────────────────────┘

📜 Immutable Audit Trail

FORTRESS implements a hybrid audit trail system using Merkle trees for efficient verification while storing detailed logs off-chain.

Architecture

┌─────────────────────────────────────────────────────────────────────┐
│                    AUDIT TRAIL ARCHITECTURE                          │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  OFF-CHAIN (Server Database)                                        │
│  ┌───────────────────────────────────────────────────────────────┐ │
│  │                                                               │ │
│  │  ┌─────────┐   ┌─────────┐   ┌─────────┐   ┌─────────┐      │ │
│  │  │ Entry 1 │──▶│ Entry 2 │──▶│ Entry 3 │──▶│ Entry 4 │      │ │
│  │  │ Hash: H1│   │ Hash: H2│   │ Hash: H3│   │ Hash: H4│      │ │
│  │  │ Prev: ∅ │   │ Prev: H1│   │ Prev: H2│   │ Prev: H3│      │ │
│  │  └─────────┘   └─────────┘   └─────────┘   └─────────┘      │ │
│  │       │             │             │             │            │ │
│  │       └─────────────┴──────┬──────┴─────────────┘            │ │
│  │                            │                                  │ │
│  │                            ▼                                  │ │
│  │                    ┌──────────────┐                          │ │
│  │                    │ Merkle Tree  │                          │ │
│  │                    │              │                          │ │
│  │                    │   [Root]     │                          │ │
│  │                    │    / \       │                          │ │
│  │                    │  [H12] [H34] │                          │ │
│  │                    │  / \   / \   │                          │ │
│  │                    │ H1 H2 H3 H4  │                          │ │
│  │                    └──────────────┘                          │ │
│  │                            │                                  │ │
│  └────────────────────────────┼──────────────────────────────────┘ │
│                               │                                     │
│                               ▼ Merkle Root                         │
│  ON-CHAIN (Blockchain)                                              │
│  ┌───────────────────────────────────────────────────────────────┐ │
│  │  AuditTrail.sol                                               │ │
│  │  ┌─────────────────────────────────────────────────────────┐ │ │
│  │  │ Batch 1: { root: 0x..., timestamp: ..., count: 4 }      │ │ │
│  │  │ Batch 2: { root: 0x..., timestamp: ..., count: 5 }      │ │ │
│  │  │ Batch 3: { root: 0x..., timestamp: ..., count: 3 }      │ │ │
│  │  └─────────────────────────────────────────────────────────┘ │ │
│  └───────────────────────────────────────────────────────────────┘ │
│                                                                      │
└─────────────────────────────────────────────────────────────────────┘

Why Merkle Trees?

Benefit Description
Efficient Verification O(log n) instead of O(n)
Partial Verification Verify one entry without all data
Tamper Detection Any modification breaks the proof
Minimal On-Chain Storage Only 32-byte root stored on-chain
Blockchain Anchoring Immutable trusted timestamp

Audit Entry Format

{
  "id": "entry-12345",
  "index": 12345,
  "timestamp": "2024-01-15T10:30:00.000Z",
  "eventType": 9,
  "eventTypeName": "FRAUD_DETECTED",
  "actor": "0x1234...abcd",
  "details": {
    "transactionId": "tx-789",
    "anomalyScore": 85,
    "flags": ["LARGE_AMOUNT", "NEW_ADDRESS_HIGH_VALUE"]
  },
  "previousHash": "0xabc123...",
  "entryHash": "0xdef456..."
}

Event Types Logged

Event Type Code Description
AUTH_LOGIN 0 Successful wallet authentication
AUTH_LOGOUT 1 Session end
AUTH_FAILURE 2 Failed authentication attempt
ROLE_ASSIGNED 3 Role granted to user
ROLE_REVOKED 4 Role removed from user
TRANSACTION_CREATED 5 New transaction submitted
TRANSACTION_FLAGGED 6 Transaction marked suspicious
ACCOUNT_FROZEN 7 Account frozen by admin/system
ACCOUNT_UNFROZEN 8 Account unfrozen
FRAUD_DETECTED 9 Anomaly detection triggered
ADMIN_ACTION 10 Administrative action
SYSTEM_CONFIG 11 System configuration change

Verification Process

┌─────────────────────────────────────────────────────────────────────┐
│                    MERKLE PROOF VERIFICATION                         │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  Step 1: Request Verification                                       │
│  ─────────────────────────────                                      │
│  User clicks "Verify" on audit entry                                │
│                                                                      │
│  Step 2: Get Merkle Proof                                           │
│  ──────────────────────────                                         │
│  Server returns:                                                     │
│  • Entry hash                                                        │
│  • Merkle proof (sibling hashes)                                    │
│  • Expected Merkle root                                              │
│                                                                      │
│  Step 3: Local Recomputation                                        │
│  ────────────────────────────                                        │
│  Client computes root from entry hash + proof:                      │
│                                                                      │
│       [Computed Root]                                                │
│            / \                                                       │
│       [Hash]  [Proof[0]]                                            │
│        / \                                                           │
│  [Entry] [Proof[1]]                                                 │
│                                                                      │
│  Step 4: Blockchain Comparison                                      │
│  ─────────────────────────────                                       │
│  Compare computed root with on-chain stored root                    │
│                                                                      │
│  Result:                                                             │
│  • ✅ Match → Entry is authentic and untampered                     │
│  • ❌ Mismatch → Tampering detected!                                │
│                                                                      │
└─────────────────────────────────────────────────────────────────────┘

🏗️ Architecture

System Overview

┌─────────────────────────────────────────────────────────────────────┐
│                      FORTRESS ARCHITECTURE                           │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  ┌─────────────────────────────────────────────────────────────────┐│
│  │                        FRONTEND (React)                         ││
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────────┐ ││
│  │  │   Home      │  │   Admin     │  │      Audit Logs         │ ││
│  │  │ (User Txns) │  │ (Dashboard) │  │ (Merkle Verification)   │ ││
│  │  └─────────────┘  └─────────────┘  └─────────────────────────┘ ││
│  └─────────────────────────────────────────────────────────────────┘│
│                               │                                      │
│                               ▼                                      │
│  ┌─────────────────────────────────────────────────────────────────┐│
│  │                     BACKEND (Node.js/Express)                   ││
│  │  ┌───────────┐  ┌────────────────┐  ┌───────────────────────┐  ││
│  │  │   Auth    │  │     Fraud      │  │      Audit            │  ││
│  │  │  Service  │  │   Detection    │  │     Service           │  ││
│  │  └───────────┘  └────────────────┘  └───────────────────────┘  ││
│  └─────────────────────────────────────────────────────────────────┘│
│                               │                                      │
│                               ▼                                      │
│  ┌─────────────────────────────────────────────────────────────────┐│
│  │                   BLOCKCHAIN (Ethereum/Hardhat)                 ││
│  │  ┌────────────────┐  ┌────────────────┐  ┌──────────────────┐  ││
│  │  │Fortress        │  │  FortressRBAC  │  │   AuditTrail     │  ││
│  │  │Transactions    │  │  (Access Ctrl) │  │ (Merkle Roots)   │  ││
│  │  └────────────────┘  └────────────────┘  └──────────────────┘  ││
│  └─────────────────────────────────────────────────────────────────┘│
│                                                                      │
└─────────────────────────────────────────────────────────────────────┘

Technology Stack

Layer Technology Purpose
Frontend React 17, TailwindCSS User interface
State React Context State management
Backend Node.js, Express API server
Auth JWT, Signature Verification Authentication
Blockchain Solidity 0.8, Hardhat Smart contracts
Crypto Web Crypto API, ethers.js Encryption

🚀 Getting Started

Prerequisites

  • Node.js 18+
  • npm or yarn
  • MetaMask browser extension
  • Git

Installation

# Clone the repository
git clone https://github.com/your-repo/fortress.git
cd fortress

# Install smart contract dependencies
cd smart_contract
npm install

# Deploy contracts (local network)
npx hardhat node
npx hardhat run scripts/deploy.js --network localhost

# Install server dependencies
cd ../server
npm install

# Install client dependencies
cd ../client
npm install

# Start services
# Terminal 1: Hardhat node
cd smart_contract && npx hardhat node

# Terminal 2: Backend server
cd server && npm run dev

# Terminal 3: Frontend
cd client && npm run dev

Environment Variables

# server/.env
PORT=5000
JWT_SECRET=your-secret-key
BLOCKCHAIN_RPC_URL=http://localhost:8545
ADMIN_PRIVATE_KEY=your-admin-private-key
FORTRESS_RBAC_ADDRESS=0x...
FORTRESS_TRANSACTIONS_ADDRESS=0x...
AUDIT_TRAIL_ADDRESS=0x...

# client/.env
VITE_API_URL=http://localhost:5000
VITE_CONTRACT_ADDRESS=0x...

📁 Project Structure

fortress/
├── client/                      # React Frontend
│   ├── src/
│   │   ├── components/
│   │   │   ├── AdminDashboard.jsx   # Admin transaction view
│   │   │   ├── AuditLogs.jsx        # Audit trail viewer
│   │   │   ├── Navbar.jsx           # Navigation
│   │   │   ├── Transactions.jsx     # User transactions
│   │   │   └── Welcome.jsx          # Home/Send form
│   │   ├── context/
│   │   │   └── TransactionContext.jsx
│   │   └── utils/
│   │       ├── encryption.js        # E2EE implementation
│   │       ├── authService.js       # Authentication
│   │       ├── fraudService.js      # Fraud detection API
│   │       └── auditService.js      # Audit trail API
│   └── package.json
│
├── server/                      # Node.js Backend
│   ├── routes/
│   │   ├── auth.js                  # Authentication endpoints
│   │   ├── fraud.js                 # Fraud detection endpoints
│   │   └── audit.js                 # Audit trail endpoints
│   ├── services/
│   │   ├── fraudDetectionService.js # Anomaly detection
│   │   └── auditLogService.js       # Merkle tree & logging
│   └── package.json
│
├── smart_contract/              # Solidity Contracts
│   ├── contracts/
│   │   ├── FortressTransactions.sol # Main transactions
│   │   ├── FortressRBAC.sol         # Access control
│   │   ├── AuditTrail.sol           # Merkle root storage
│   │   └── FortressTransactionsE2EE.sol # E2EE support
│   ├── test/
│   │   ├── FortressRBAC.test.js
│   │   └── AuditTrail.test.js
│   └── package.json
│
└── README.md

📚 API Reference

Authentication

Endpoint Method Description
/auth/nonce GET Get nonce for signing
/auth/verify POST Verify signature, get JWT
/auth/session GET Validate current session
/auth/roles GET Get user roles from blockchain
/auth/logout POST End session

Fraud Detection

Endpoint Method Description
/fraud/analyze POST Analyze transaction
/fraud/status/:address GET Get account status
/fraud/config GET Get detection config
/fraud/audit GET Get enforcement log

Audit Trail

Endpoint Method Description
/audit/my-entries GET Get user's audit entries
/audit/entries GET Get all entries (auditor)
/audit/verify POST Verify entry with Merkle proof
/audit/verify-chain GET Verify chain integrity
/audit/stats GET Get audit statistics
/audit/commit POST Force batch commit (admin)

📄 Smart Contracts

FortressRBAC.sol

Access control with account freezing capabilities.

// Key functions
function assignUserRole(address account) external;
function assignAdminRole(address account) external;
function freezeAccount(address account, string reason) external;
function unfreezeAccount(address account) external;

FortressTransactions.sol

Main transaction contract with E2EE support.

// Key functions
function addToBlockchain(address receiver, uint amount, string message, string keyword) external;
function getAllTransactions() external view returns (TransferStruct[] memory);
function flagTransaction(uint transactionId, string reason) external;

AuditTrail.sol

Merkle root storage and verification.

// Key functions
function submitAuditBatch(bytes32 merkleRoot, uint entryCount, ...) external;
function verifyEntry(uint batchId, bytes32 entryHash, bytes32[] proof) external view returns (bool);
function verifyBatchChain(uint fromBatchId, uint toBatchId) external view returns (bool);

🔒 Security Considerations

Do's ✅

  • Always verify signatures server-side
  • Use secure random for key generation
  • Store private keys only in session storage
  • Enforce roles on-chain, not just UI
  • Log all sensitive actions for audit
  • Use nonces to prevent replay attacks

Don'ts ❌

  • Never transmit private keys
  • Never store plaintext secrets
  • Never trust frontend-only checks
  • Never skip signature verification
  • Never allow log modification
  • Never store full logs on-chain

📝 License

This project is licensed under the MIT License - see the LICENSE file for details.


🙏 Acknowledgments


Built with 🔐 Security First

Report Bug · Request Feature

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors