SECTION 1: LEARNING OBJECTIVES

By the end of this lesson, you will be able to:

  • Define the role of blockchain in healthcare and life sciences.

  • Explain the management of medical records on blockchain.

  • Understand drug provenance and supply chain integrity.

  • Describe clinical trial data management and patient consent.

  • Identify key blockchain healthcare platforms.

  • Analyse privacy and data sharing challenges.

  • Implement a healthcare data management simulation in Python.

  • Develop a framework for blockchain adoption in healthcare.


SECTION 2: HEALTHCARE CHALLENGES

2.1 The Healthcare Data Problem

text
┌─────────────────────────────────────────────────────────────────────────────┐
│                    HEALTHCARE DATA CHALLENGES                               │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    DATA SILOS                                        │   │
│  │  Patient data is fragmented across providers, hospitals, and payers. │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    PRIVACY CONCERNS                                  │   │
│  │  Sensitive health data vulnerable to breaches.                      │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    COUNTERFEIT DRUGS                                 │   │
│  │  $200B+ annual market in counterfeit pharmaceuticals.               │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    CLINICAL TRIAL DATA INTEGRITY                    │   │
│  │  Data manipulation and selective reporting issues.                  │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    PATIENT CONSENT MANAGEMENT                       │   │
│  │  Fragmented and outdated consent records.                           │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

2.2 Blockchain Solutions

 
 
Challenge Blockchain Solution Benefit
Data Silos Decentralised health records Interoperable, accessible
Privacy ZKPs, encryption, selective disclosure Patient-controlled
Counterfeit Drugs Track-and-trace blockchain Provenance, authenticity
Trial Integrity Immutable trial data Trust, transparency
Consent Management Smart contract consent Automated, auditable

SECTION 3: KEY APPLICATIONS

3.1 Medical Records Management

text
┌─────────────────────────────────────────────────────────────────────────────┐
│                    BLOCKCHAIN MEDICAL RECORDS                               │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  PATIENT                                                                   │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │  • Owns private key                                                 │   │
│  │  • Controls access                                                 │   │
│  │  • Grants permissions                                              │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    BLOCKCHAIN NETWORK                                │   │
│  │  • Encrypted health records                                        │   │
│  │  • Access logs                                                      │   │
│  │  • Consent records                                                 │   │
│  │  • Audit trails                                                    │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                    ┌───────────────┼───────────────┐                      │
│                    v               v               v                      │
│  ┌──────────────────┐  ┌──────────────────┐  ┌──────────────────┐        │
│  │  Hospital        │  │  Specialist      │  │  Researcher      │        │
│  │  • Access record │  │  • Add data      │  │  • Anonymised    │        │
│  │  • Update        │  │  • Prescribe     │  │  • Aggregate     │        │
│  └──────────────────┘  └──────────────────┘  └──────────────────┘        │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

3.2 Drug Supply Chain

 
 
Stage Traditional Blockchain-Enabled
Manufacturing Batch records On-chain batch IDs
Distribution Paper tracking GPS + blockchain
Warehousing Manual inventory Smart contract management
Pharmacy Verification challenges Tamper-proof verification
Patient No provenance Full traceability

SECTION 4: KEY PLATFORMS AND PLAYERS

 
 
Platform Description Focus
MediLedger Pharmaceutical supply chain Drug provenance, track-and-trace
Medicalchain Medical records platform Patient-controlled records
Solve.Care Healthcare coordination Care management, payments
Guardtime Healthcare data integrity Data provenance, audit
Hashed Health Healthcare blockchain consortium Standards, interoperability
Chronicled Pharmaceutical supply chain Compliance, traceability

SECTION 5: IMPLEMENTATION IN PYTHON

python
# ===================================================================
# MODULE 3, LESSON 6: HEALTHCARE AND LIFE SCIENCES
# ===================================================================

import hashlib
import time
import random
import json
from typing import Dict, List, Optional, Tuple
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')

print("="*70)
print("HEALTHCARE AND LIFE SCIENCES – BLOCKCHAIN APPLICATIONS")
print("="*70)

# ----------------------------------------------------------------
# PART A: PATIENT HEALTH RECORD SIMULATION
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART A: Patient Health Record Simulation on Blockchain")
print("-"*60)

class HealthRecord:
    """
    Simulated health record on blockchain.
    """
    def __init__(self, patient_id: str, patient_name: str):
        self.patient_id = patient_id
        self.patient_name = patient_name
        self.records: List[Dict] = []
        self.access_logs: List[Dict] = []
        self.consent_records: List[Dict] = []
        self.created_at = datetime.now()
        self.patient_private_key = hashlib.sha256(f"{patient_id}_private".encode()).hexdigest()[:16]
    
    def add_medical_record(self, provider: str, record_type: str, data: Dict) -> Dict:
        """Add a medical record to the blockchain."""
        record = {
            'record_id': f'REC-{len(self.records)+1:06d}',
            'patient_id': self.patient_id,
            'provider': provider,
            'record_type': record_type,
            'data': data,
            'timestamp': datetime.now(),
            'hash': self._hash_record(record_type, data),
            'status': 'Active'
        }
        self.records.append(record)
        print(f"Added {record_type} record for {self.patient_name}")
        return record
    
    def _hash_record(self, record_type: str, data: Dict) -> str:
        """Generate a hash for the record."""
        content = f"{self.patient_id}{record_type}{json.dumps(data)}{time.time()}"
        return hashlib.sha256(content.encode()).hexdigest()[:16]
    
    def grant_access(self, provider: str, record_types: List[str], duration_days: int) -> Dict:
        """Grant access to a provider."""
        consent = {
            'consent_id': f'CON-{len(self.consent_records)+1:06d}',
            'patient': self.patient_id,
            'provider': provider,
            'record_types': record_types,
            'granted_at': datetime.now(),
            'expires_at': datetime.now() + timedelta(days=duration_days),
            'active': True,
            'signature': hashlib.sha256(f"{self.patient_id}{provider}{time.time()}".encode()).hexdigest()[:16]
        }
        self.consent_records.append(consent)
        print(f"Access granted to {provider} for {', '.join(record_types)} ({duration_days} days)")
        return consent
    
    def get_consent_status(self, provider: str) -> bool:
        """Check if provider has valid consent."""
        for consent in self.consent_records:
            if consent['provider'] == provider and consent['active']:
                if consent['expires_at'] > datetime.now():
                    return True
        return False
    
    def get_records_by_type(self, record_type: str) -> List[Dict]:
        """Get all records of a specific type."""
        return [r for r in self.records if r['record_type'] == record_type]
    
    def get_medical_summary(self) -> Dict:
        """Get a summary of all medical records."""
        summary = {
            'patient_id': self.patient_id,
            'patient_name': self.patient_name,
            'total_records': len(self.records),
            'record_types': list(set(r['record_type'] for r in self.records)),
            'last_record': self.records[-1]['timestamp'] if self.records else None,
            'consents_active': len([c for c in self.consent_records if c['active'] and c['expires_at'] > datetime.now()])
        }
        return summary

# Create patient records
alice_health = HealthRecord('P001', 'Alice Johnson')

print("Creating patient health records...")

# Add medical records
alice_health.add_medical_record(
    provider='Dr. Smith',
    record_type='Vital Signs',
    data={'blood_pressure': '120/80', 'heart_rate': 72, 'temperature': 98.6, 'weight': 68, 'height': 165}
)

alice_health.add_medical_record(
    provider='Dr. Johnson',
    record_type='Lab Results',
    data={'cholesterol': 190, 'glucose': 95, 'hemoglobin': 14.5, 'wbc': 7.2}
)

alice_health.add_medical_record(
    provider='Dr. Smith',
    record_type='Diagnosis',
    data={'condition': 'Hypertension', 'severity': 'Mild', 'diagnosed_date': '2024-01-15'}
)

alice_health.add_medical_record(
    provider='Dr. Williams',
    record_type='Prescription',
    data={'medication': 'Lisinopril', 'dosage': '10mg', 'frequency': 'daily', 'prescribed': '2024-01-15'}
)

# Grant access
alice_health.grant_access('Dr. Smith', ['Vital Signs', 'Diagnosis', 'Prescription'], 365)
alice_health.grant_access('Dr. Williams', ['Lab Results', 'Prescription'], 180)

# Display medical summary
print("\nPatient Medical Summary:")
summary = alice_health.get_medical_summary()
for key, value in summary.items():
    print(f"  {key}: {value}")

# ----------------------------------------------------------------
# PART B: DRUG SUPPLY CHAIN SIMULATION
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART B: Drug Supply Chain Traceability")
print("-"*60)

class DrugBatch:
    """
    Represents a batch of pharmaceutical products.
    """
    def __init__(self, batch_id: str, drug_name: str, manufacturer: str, quantity: int, expiry: datetime):
        self.batch_id = batch_id
        self.drug_name = drug_name
        self.manufacturer = manufacturer
        self.quantity = quantity
        self.expiry = expiry
        self.transactions: List[Dict] = []
        self.current_location = manufacturer
        self.status = 'Manufactured'
        self.created_at = datetime.now()
        self.hash = hashlib.sha256(f"{batch_id}{manufacturer}{time.time()}".encode()).hexdigest()[:16]
    
    def add_transaction(self, from_location: str, to_location: str, quantity: int, custodian: str):
        """Record a supply chain transaction."""
        tx = {
            'batch_id': self.batch_id,
            'from': from_location,
            'to': to_location,
            'quantity': quantity,
            'custodian': custodian,
            'timestamp': datetime.now(),
            'tx_hash': hashlib.sha256(f"{self.batch_id}{from_location}{to_location}{quantity}{time.time()}".encode()).hexdigest()[:16]
        }
        self.transactions.append(tx)
        self.current_location = to_location
        self.quantity -= quantity
        print(f"Transaction: {quantity} units of {self.drug_name} moved from {from_location} to {to_location}")
        return tx
    
    def get_provenance(self) -> List[Dict]:
        """Get full provenance of the drug batch."""
        return self.transactions
    
    def is_expired(self) -> bool:
        return datetime.now() > self.expiry
    
    def get_summary(self) -> Dict:
        return {
            'batch_id': self.batch_id,
            'drug_name': self.drug_name,
            'manufacturer': self.manufacturer,
            'remaining_quantity': self.quantity,
            'current_location': self.current_location,
            'status': self.status,
            'expiry': self.expiry,
            'is_expired': self.is_expired(),
            'transactions': len(self.transactions)
        }

class DrugSupplyChain:
    """
    Simulated drug supply chain on blockchain.
    """
    def __init__(self):
        self.batches: List[DrugBatch] = []
        self.verification_requests = []
    
    def create_batch(self, drug_name: str, manufacturer: str, quantity: int, expiry_days: int) -> DrugBatch:
        batch_id = f'BATCH-{len(self.batches)+1:06d}'
        expiry = datetime.now() + timedelta(days=expiry_days)
        batch = DrugBatch(batch_id, drug_name, manufacturer, quantity, expiry)
        self.batches.append(batch)
        print(f"\nBatch Created: {batch_id}")
        print(f"  Drug: {drug_name}")
        print(f"  Manufacturer: {manufacturer}")
        print(f"  Quantity: {quantity}")
        print(f"  Expiry: {expiry.strftime('%Y-%m-%d')}")
        return batch
    
    def move_batch(self, batch_id: str, from_location: str, to_location: str, quantity: int, custodian: str):
        """Move a batch along the supply chain."""
        batch = next((b for b in self.batches if b.batch_id == batch_id), None)
        if not batch:
            print(f"Batch {batch_id} not found")
            return None
        if batch.quantity < quantity:
            print(f"Insufficient quantity. Available: {batch.quantity}")
            return None
        
        return batch.add_transaction(from_location, to_location, quantity, custodian)
    
    def verify_batch(self, batch_id: str) -> Dict:
        """Verify the authenticity of a drug batch."""
        batch = next((b for b in self.batches if b.batch_id == batch_id), None)
        if not batch:
            return {'verified': False, 'message': 'Batch not found'}
        
        if batch.is_expired():
            return {'verified': False, 'message': 'Batch is expired'}
        
        # Verify the chain of custody
        if not batch.transactions:
            return {'verified': False, 'message': 'No supply chain records'}
        
        return {
            'verified': True,
            'batch_id': batch_id,
            'drug_name': batch.drug_name,
            'manufacturer': batch.manufacturer,
            'current_location': batch.current_location,
            'remaining_quantity': batch.quantity,
            'provenance': len(batch.transactions),
            'is_expired': batch.is_expired()
        }
    
    def get_chain_summary(self) -> pd.DataFrame:
        """Get summary of all batches in the supply chain."""
        summaries = [b.get_summary() for b in self.batches]
        return pd.DataFrame(summaries)

# Create supply chain
supply_chain = DrugSupplyChain()

# Create drug batches
batch1 = supply_chain.create_batch(
    drug_name='Aspirin',
    manufacturer='PharmaCorp',
    quantity=10000,
    expiry_days=730
)

batch2 = supply_chain.create_batch(
    drug_name='Antibiotic',
    manufacturer='MediTech',
    quantity=5000,
    expiry_days=365
)

# Simulate supply chain movements
print("\n--- Supply Chain Movements ---")
supply_chain.move_batch(batch1.batch_id, 'PharmaCorp', 'Distributor_A', 3000, 'Logistics_Co')
supply_chain.move_batch(batch1.batch_id, 'Distributor_A', 'Pharmacy_Central', 1000, 'Pharmacy_Co')
supply_chain.move_batch(batch2.batch_id, 'MediTech', 'Distributor_B', 2000, 'Logistics_Co')
supply_chain.move_batch(batch2.batch_id, 'Distributor_B', 'Hospital_A', 500, 'Hospital_Supply')

# Verify batches
print("\n--- Batch Verification ---")
for batch_id in [batch1.batch_id, batch2.batch_id]:
    result = supply_chain.verify_batch(batch_id)
    print(f"\nBatch {batch_id}: {'✅ Verified' if result['verified'] else '❌ Not Verified'}")
    if result['verified']:
        print(f"  Drug: {result['drug_name']}")
        print(f"  Location: {result['current_location']}")
        print(f"  Remaining: {result['remaining_quantity']}")

# ----------------------------------------------------------------
# PART C: CLINICAL TRIAL DATA MANAGEMENT
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART C: Clinical Trial Data Management")
print("-"*60)

class ClinicalTrial:
    """
    Simulated clinical trial with blockchain data integrity.
    """
    def __init__(self, trial_id: str, name: str, sponsor: str, phase: str, start_date: datetime):
        self.trial_id = trial_id
        self.name = name
        self.sponsor = sponsor
        self.phase = phase
        self.start_date = start_date
        self.participants: List[Dict] = []
        self.data_points: List[Dict] = []
        self.data_hashes: List[str] = []
        self.status = 'Recruiting'
    
    def register_participant(self, participant_id: str, age: int, gender: str, condition: str) -> Dict:
        participant = {
            'participant_id': participant_id,
            'age': age,
            'gender': gender,
            'condition': condition,
            'enrolled_at': datetime.now(),
            'status': 'Active'
        }
        self.participants.append(participant)
        print(f"Participant {participant_id} enrolled in {self.name}")
        return participant
    
    def add_data_point(self, participant_id: str, data_type: str, value: float, unit: str) -> Dict:
        """Add a data point with blockchain hash for integrity."""
        data_point = {
            'trial_id': self.trial_id,
            'participant_id': participant_id,
            'data_type': data_type,
            'value': value,
            'unit': unit,
            'timestamp': datetime.now(),
            'hash': hashlib.sha256(f"{participant_id}{data_type}{value}{time.time()}".encode()).hexdigest()[:16]
        }
        self.data_points.append(data_point)
        self.data_hashes.append(data_point['hash'])
        return data_point
    
    def get_data_summary(self) -> Dict:
        """Get summary of all data points."""
        data_types = list(set(d['data_type'] for d in self.data_points))
        return {
            'trial_id': self.trial_id,
            'name': self.name,
            'phase': self.phase,
            'participants': len(self.participants),
            'data_points': len(self.data_points),
            'data_types': data_types,
            'status': self.status
        }
    
    def verify_integrity(self) -> bool:
        """Verify data integrity using hashes."""
        # Simple verification: ensure all hashes exist and are unique
        if not self.data_hashes:
            return True
        return len(self.data_hashes) == len(set(self.data_hashes))

# Create clinical trial
trial = ClinicalTrial(
    trial_id='CT-001',
    name='Blockchain Diabetes Study',
    sponsor='MediResearch',
    phase='Phase II',
    start_date=datetime.now() - timedelta(days=30)
)

print("\nClinical Trial Created:")
print(f"  Name: {trial.name}")
print(f"  Phase: {trial.phase}")
print(f"  Sponsor: {trial.sponsor}")

# Register participants
participants = [
    ('P001', 45, 'M', 'Type 2 Diabetes'),
    ('P002', 52, 'F', 'Type 2 Diabetes'),
    ('P003', 38, 'M', 'Type 1 Diabetes'),
    ('P004', 60, 'F', 'Type 2 Diabetes'),
    ('P005', 41, 'M', 'Prediabetes')
]

print("\nEnrolling participants...")
for p_id, age, gender, condition in participants:
    trial.register_participant(p_id, age, gender, condition)

# Add data points
print("\nAdding trial data points...")
data_types = ['glucose_mg_dL', 'insulin_units', 'weight_kg', 'blood_pressure_sys', 'blood_pressure_dia']

for participant in trial.participants:
    for i in range(5):
        data_type = random.choice(data_types)
        if data_type == 'glucose_mg_dL':
            value = random.uniform(80, 250)
        elif data_type == 'insulin_units':
            value = random.uniform(5, 50)
        elif data_type == 'weight_kg':
            value = random.uniform(50, 120)
        else:
            value = random.uniform(100, 180)
        trial.add_data_point(participant['participant_id'], data_type, value, 'units')

# Get trial summary
summary = trial.get_data_summary()
print("\nTrial Summary:")
for key, value in summary.items():
    print(f"  {key}: {value}")

print(f"\nData Integrity Verified: {trial.verify_integrity()}")

# ----------------------------------------------------------------
# PART D: HEALTHCARE DATA VISUALISATION
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART D: Healthcare Data Visualisation")
print("-"*60)

# Create visualisations
fig, axes = plt.subplots(2, 2, figsize=(14, 10))

# 1. Trial data types distribution
ax1 = axes[0, 0]
data_types = [d['data_type'] for d in trial.data_points]
data_type_counts = pd.Series(data_types).value_counts()
ax1.pie(data_type_counts.values, labels=data_type_counts.index, autopct='%1.1f%%', startangle=90)
ax1.set_title('Clinical Trial Data Types')

# 2. Drug supply chain distribution
ax2 = axes[0, 1]
batch_summary = supply_chain.get_chain_summary()
if not batch_summary.empty:
    ax2.bar(batch_summary['drug_name'], batch_summary['remaining_quantity'], color='teal', alpha=0.7)
    ax2.set_ylabel('Remaining Quantity')
    ax2.set_title('Drug Supply Chain Inventory')
    ax2.grid(True, alpha=0.3)

# 3. Participant demographics
ax3 = axes[1, 0]
ages = [p['age'] for p in trial.participants]
genders = [p['gender'] for p in trial.participants]
age_df = pd.DataFrame({'age': ages, 'gender': genders})
sns.boxplot(data=age_df, x='gender', y='age', ax=ax3, palette=['#ff9999', '#66b3ff'])
ax3.set_title('Participant Age Distribution by Gender')
ax3.grid(True, alpha=0.3)

# 4. Data integrity count
ax4 = axes[1, 1]
# Simulate healthcare data integrity metrics
integrity_metrics = {
    'Total Records': 150,
    'Verified Records': 148,
    'Unverified Records': 2,
    'Integrity Score': 98.7
}
ax4.bar(integrity_metrics.keys(), integrity_metrics.values(), color=['green', 'green', 'red', 'blue'], alpha=0.7)
ax4.set_ylabel('Count')
ax4.set_title('Data Integrity Metrics')
ax4.grid(True, alpha=0.3)
plt.setp(ax4.get_xticklabels(), rotation=45, ha='right')

plt.tight_layout()
plt.savefig('healthcare_blockchain.png', dpi=300, bbox_inches='tight')
plt.show()
print("Healthcare blockchain chart saved as 'healthcare_blockchain.png'")

# ----------------------------------------------------------------
# PART E: HEALTHCARE USE CASES AND BENEFITS
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART E: Healthcare Use Cases and Benefits")
print("-"*60)

use_cases = pd.DataFrame({
    'Use Case': [
        'Medical Records',
        'Drug Provenance',
        'Clinical Trials',
        'Patient Consent',
        'Supply Chain',
        'Health Insurance'
    ],
    'Blockchain Application': [
        'Decentralised records',
        'Track-and-trace',
        'Immutable data',
        'Smart contracts',
        'End-to-end tracking',
        'Smart claims'
    ],
    'Key Benefit': [
        'Patient control',
        'Fraud prevention',
        'Data integrity',
        'Automated compliance',
        'Counterfeit detection',
        'Automated processing'
    ],
    'Adoption Level': [
        'Early Growth',
        'Growing',
        'Emerging',
        'Early',
        'Growing',
        'Early'
    ]
})

print(use_cases.to_string(index=False))

# ----------------------------------------------------------------
# PART F: SUMMARY AND RECOMMENDATIONS
# ----------------------------------------------------------------

print("\n" + "="*70)
print("PART F: Summary and Recommendations")
print("="*70)

print("""
Healthcare and Life Sciences with Blockchain – Key Takeaways:

1. Blockchain addresses data silos, privacy, counterfeit drugs, and trial integrity.
2. Medical records: patient-controlled, secure, interoperable.
3. Drug supply chain: track-and-trace for authenticity and safety.
4. Clinical trials: immutable data, transparent results, patient consent.
5. Key platforms: MediLedger, Medicalchain, Solve.Care, Guardtime.
6. Benefits: patient empowerment, fraud reduction, data integrity.
7. Challenges: interoperability, regulation, adoption barriers.

Recommendations:
  - Start with a focused use case (e.g., drug provenance).
  - Ensure HIPAA/GDPR compliance for patient data.
  - Build interoperable systems with existing healthcare IT.
  - Educate stakeholders on blockchain benefits.
  - Use zero-knowledge proofs for privacy.
  - Integrate with IoT for real-time data collection.
  - Consider permissioned blockchains for healthcare.
""")