This document outlines the complete implementation of a healthcare system with blockchain integration for medical record integrity verification. The system combines off-chain storage (IPFS) with on-chain hash verification to ensure data integrity while maintaining privacy and efficiency.
- Frontend (React) - User interface for patients and doctors
- Backend (Node.js/Express) - API server with authentication and business logic
- Database (MongoDB) - Store user data and metadata
- IPFS - Decentralized storage for encrypted medical files
- Blockchain (Ethereum/Sepolia) - Smart contracts for hash integrity verification
- Encryption - AES-256-CBC for file encryption using wallet signatures
Patient Upload → Encrypt File → Store in IPFS → Store Hash on Blockchain → Store Metadata in Database
Doctor Request → Patient Approval → Blockchain Access Grant → Decrypt & Verify Integrity
The main contract stores:
- Patient information (name, age, gender, etc.)
- Medical record hashes (prescriptions, bills, reports)
- Access control (doctors requesting and getting approval)
- Expiry management for time-limited access
Key Functions:
addPrescription(name, dataHash)- Store prescription hashaddBill(name, dataHash)- Store bill hashaddReport(name, dataHash)- Store report hashrequestAccess()- Doctor requests accessapproveAccess(doctor, duration, recordIds)- Patient approves accessgetApprovedRecords()- Get approved records for doctor
Handles all blockchain interactions:
- Deploy patient contracts via factory
- Add record hashes to blockchain
- Grant/revoke access permissions
- Retrieve approved records for doctors
- Get specific record hashes for verification
Manages the complete file lifecycle:
- Generate file hash (SHA-256)
- Encrypt file with patient's wallet signature-derived key
- Upload encrypted file to IPFS
- Store hash on patient's blockchain contract
- Save metadata to MongoDB
- Fetch encrypted file from IPFS
- Decrypt using patient's key (for owners) or stored key (for doctors)
- Verify integrity against local database hash
- Verify integrity against blockchain hash
- Return file if verification passes
Handles doctor-patient access workflow:
- Doctor creates access request with wallet address
- System stores request in database
- Patient receives notification
- Patient selects records to share
- Patient provides wallet signature for key generation
- System updates database permissions
- System calls blockchain
approveAccess()function - Doctor gains access to selected records
Provides integrity verification utilities:
- Verify file against database hash
- Verify file against blockchain hash
- Batch verification for multiple records
- Generate integrity reports
Testing and monitoring endpoints:
- System health checks
- Patient workflow testing
- Doctor workflow testing
- Blockchain integration testing
- Integrity reporting
POST /api/medical-records/upload - Upload encrypted medical record
GET /api/medical-records/view/:ipfsHash - Download and decrypt record
GET /api/medical-records/verify/:ipfsHash - Verify record integrity
GET /api/medical-records/patient-records - Get patient's records
POST /api/access-requests/doctor/request - Doctor requests access
GET /api/access-requests/patient/requests - Get patient's pending requests
POST /api/access-requests/patient/respond - Patient approves/denies access
GET /api/access-requests/doctor/authorized-records - Get doctor's authorized records
GET /api/access-requests/doctor/blockchain-authorized-records - Get blockchain-verified records
GET /api/system/status - System health check
GET /api/system/test/patient-workflow - Test patient workflow
GET /api/system/test/doctor-workflow - Test doctor workflow
GET /api/system/test/blockchain/:contractAddress - Test contract integration
GET /api/system/integrity-report - Generate integrity report
- Files encrypted with AES-256-CBC
- Keys derived from wallet signatures (deterministic)
- Unique IV for each file
- Patient can always regenerate keys from signature
- JWT-based authentication
- Role-based permissions (patient/doctor)
- Time-limited access grants
- Blockchain-enforced permissions
- SHA-256 hashes stored on blockchain
- Double verification (database + blockchain)
- Tamper detection through hash comparison
- Immutable audit trail
// Frontend: Patient signs message with wallet
const signature = await signer.signMessage("Healthcare Record Upload");
// API call with file and signature
const formData = new FormData();
formData.append('file', file);
formData.append('recordType', 'prescription');
formData.append('name', 'Blood Test Results');
formData.append('walletSignature', signature);
const response = await fetch('/api/medical-records/upload', {
method: 'POST',
body: formData,
headers: { Authorization: `Bearer ${token}` }
});const response = await fetch('/api/access-requests/doctor/request', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${doctorToken}`
},
body: JSON.stringify({
patientId: 'patient_id',
requestReason: 'Treatment planning',
walletAddress: doctorWalletAddress
})
});// Patient signs approval message
const signature = await signer.signMessage("Approve Medical Record Access");
const response = await fetch('/api/access-requests/patient/respond', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${patientToken}`
},
body: JSON.stringify({
requestId: 'request_id',
action: 'approve',
selectedRecords: ['record1_id', 'record2_id'],
accessDuration: 30, // days
patientSignature: signature
})
});// Doctor can now access the record
const response = await fetch(`/api/medical-records/view/${ipfsHash}`, {
headers: { Authorization: `Bearer ${doctorToken}` }
});
// Check integrity headers
const integrityVerified = response.headers.get('X-Integrity-Verified');
const blockchainVerified = response.headers.get('X-Blockchain-Hash-Verified');# Database
MONGODB_URI=mongodb://localhost:27017/healthcare
# JWT Secrets
ACCESSJWT_SECRET=your_jwt_secret
REFRESHJWT_SECRET=your_refresh_secret
# IPFS Configuration
IPFS_HOST=localhost
IPFS_PORT=5001
IPFS_PROTOCOL=http
# Blockchain Configuration
ETHEREUM_RPC_URL=https://sepolia.infura.io/v3/YOUR_PROJECT_ID
PRIVATE_KEY=your_private_key
HEALTH_RECORD_FACTORY_ADDRESS=0x...factory_contract_address-
Deploy Smart Contracts
cd contracts forge build forge script script/DeployHealthRecordFactory.s.sol --broadcast --rpc-url $SEPOLIA_RPC_URL
-
Setup Backend
cd backend npm install npm start -
Configure Environment
- Set contract addresses
- Configure IPFS node
- Set up MongoDB
- Configure blockchain RPC
-
Test Integration
# Test system health curl http://localhost:5000/api/system/status # Test with authenticated users curl -H "Authorization: Bearer $TOKEN" \ http://localhost:5000/api/system/test/patient-workflow
The system includes comprehensive error handling for:
- Network failures (IPFS, blockchain)
- Invalid signatures or keys
- Expired access permissions
- Hash mismatches (tampered data)
- Contract interaction failures
- IPFS files are cached locally when possible
- Blockchain calls are minimized through caching
- Database queries are optimized with indexes
- File encryption/decryption is streamed for large files
- IPFS Clustering - Multiple IPFS nodes for redundancy
- Layer 2 Integration - Use Polygon or Arbitrum for lower costs
- Advanced Encryption - Proxy re-encryption for better key management
- Audit Logging - Comprehensive access logging
- Mobile App - React Native mobile application
-
Contract Deployment Failed
- Check RPC URL and private key
- Ensure sufficient ETH for gas
-
IPFS Upload Failed
- Verify IPFS node is running
- Check network connectivity
-
Integrity Verification Failed
- File may be corrupted
- Check signature generation
- Verify contract address
-
Access Denied
- Check JWT token validity
- Verify wallet address registration
- Ensure access hasn't expired
For technical support or questions about the implementation, please refer to the system logs and use the testing endpoints to diagnose issues.