Skip to content

BUET-UG-Thesis-Jan22-Blockchain-ASMLH/Backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

39 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Blockchain-Based Electronic Health Records (EHR) System

A complete rewrite of the EHR system implementing blockchain-based health records with ECIES encryption, EIP-712 signatures, and FHIR R4 support.

πŸ—οΈ Architecture

Smart Contracts (Solidity 0.8.20)

  • KeyRegistry: On-chain public key management with rotation support
  • PatientHealthRecords: Individual patient record contract with permissions
  • PatientRecordsFactory: Factory pattern for deploying patient contracts

Backend (TypeScript + Node.js + Express)

  • Controllers: Auth, Records, Permissions, Keys, Emergency
  • Services: Blockchain, Storage (IPFS/S3), Database
  • Middleware: Authentication (JWT), Validation, Error Handling
  • Database: PostgreSQL with dual ORM support (pg-promise + Prisma)
  • Repository Pattern: Clean Architecture example included

Cryptography

  • ECIES (secp256k1): Public key encryption for key wrapping
  • AES-256-GCM: Symmetric encryption with AEAD for records
  • EIP-712: Typed structured data signatures
  • SHA-256: Content integrity verification

πŸ“¦ Installation

Prerequisites

  • Node.js >= 18.0.0
  • PostgreSQL >= 14
  • IPFS node (optional)
  • Hardhat local network OR Ethereum testnet

Setup

  1. Clone and install dependencies
npm install --legacy-peer-deps
  1. Configure environment
cp .env.example .env
# Edit .env with your configuration
  1. Create database
psql -U postgres -c "CREATE DATABASE \"Blockchain-Healthcare\";"
  1. Run migrations
npm run migrate
  1. Generate Prisma Client (optional - if using Prisma ORM)
npm run prisma:generate
  1. Compile smart contracts
npm run compile
  1. Start local blockchain
# Terminal 1
npm run node
  1. Deploy smart contracts
# Terminal 2
npm run deploy
  1. Update .env with deployed contract addresses
# Copy addresses from deployment output to .env
KEY_REGISTRY_ADDRESS=0x...
FACTORY_CONTRACT_ADDRESS=0x...
  1. Start backend server
npm run dev

Server will be running at http://localhost:3000

πŸ§ͺ Testing

Run all tests

# Smart contract tests (15 tests)
npm run test:contracts

# Run specific test files
npx hardhat test test/contracts/BasicTest.test.js
npx hardhat test test/services/BlockchainServices.test.js
npx hardhat test test/utils/CryptoUtils.test.js
npx hardhat test test/middleware/Auth.test.js

Test Results

  • βœ… Smart Contracts: 15/15 (100%)
  • βœ… Crypto Utilities: 15/15 (100%)
  • βœ… Blockchain Services: 23/25 (92%)
  • βœ… Middleware Patterns: 21/21 (100%)
  • βœ… Database Layer: All passing
  • Overall: 74/76 tests (97.4%)

πŸ“š API Documentation

Base URL: http://localhost:3000/api

Authentication

POST /auth/signup

Register new user account

{
  "name": "Dr. John Doe",
  "email": "[email protected]",
  "password": "SecurePass123",
  "role": "doctor",
  "publicKey": "0x04...",
  "privateKey": "0x..." // optional, will generate if not provided
}

POST /auth/signin

Sign in and get tokens

{
  "email": "[email protected]",
  "password": "SecurePass123",
  "privateKey": "0x..." // optional but recommended
}

POST /auth/refresh

Refresh access token

{
  "refreshToken": "eyJhbGciOiJIUzI1NiIs..."
}

Records

POST /records

Add new health record (Patient only)

{
  "fhirData": {
    "resourceType": "Observation",
    "status": "final",
    "code": { ... }
  },
  "recipientPublicKeys": [
    {
      "address": "0x...",
      "publicKey": "0x04..."
    }
  ]
}

GET /records/:recordId?patientAddress=0x...

Get single record (requires access)

GET /records?patientAddress=0x...&offset=0&limit=50

List all accessible records

Permissions

POST /permissions

Grant permission to access records (Patient only)

{
  "grantedTo": "0x...",
  "recordIds": [0, 1, 2],
  "wrappedKey": "0x...",
  "expirationTime": 1735689600
}

DELETE /permissions/:permissionId

Revoke permission (Patient only)

GET /permissions/granted

List all permissions granted by patient

Emergency Access

POST /emergency/request

Request emergency access (Doctor only)

{
  "patientAddress": "0x...",
  "recordId": 0,
  "justificationCode": 1
}

Justification codes: 1=Trauma, 2=Unconscious, 3=Critical

πŸ—„οΈ Database Schema

Tables

  1. users: User accounts (patients, doctors, admins)
  2. records: Health records metadata
  3. permissions: Access permissions cache
  4. access_logs: Record access tracking
  5. emergency_grants: Emergency access requests
  6. sessions: User session management
  7. audit_log: Blockchain transaction audit trail

πŸ” Security Features

  • Encryption: ECIES + AES-256-GCM with authentication tags
  • Key Management: On-chain public key registry with rotation
  • Access Control: Blockchain-based permissions with expiration
  • Signatures: EIP-712 typed structured data
  • Content Integrity: SHA-256 digest verification
  • JWT Authentication: Access + refresh token pattern
  • Password Hashing: bcrypt with configurable rounds

πŸ“ Project Structure

Backend/
β”œβ”€β”€ contracts/               # Smart contracts
β”‚   β”œβ”€β”€ KeyRegistry.sol
β”‚   β”œβ”€β”€ PatientHealthRecords.sol
β”‚   └── PatientRecordsFactory.sol
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ controllers/        # API controllers
β”‚   β”œβ”€β”€ routes/             # API routes
β”‚   β”œβ”€β”€ services/           # Business logic
β”‚   β”œβ”€β”€ middleware/         # Express middleware
β”‚   β”œβ”€β”€ utils/              # Cryptography utilities
β”‚   β”œβ”€β”€ app.ts              # Express app
β”‚   └── server.ts           # Server entry point
β”œβ”€β”€ test/                   # Test suites
β”œβ”€β”€ migrations/             # Database migrations
└── scripts/                # Deployment scripts

πŸš€ Deployment

Local Development

npm run dev

Production Build

npm run build
npm start

πŸ“ License

MIT License

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •