SECTION 1: LEARNING OBJECTIVES

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

  • Define digital identity and its importance in digital finance.

  • Explain the concept of Self-Sovereign Identity (SSI).

  • Understand Decentralised Identifiers (DIDs) and Verifiable Credentials (VCs).

  • Describe how blockchain transforms KYC/AML processes.

  • Differentiate between centralised, federated, and decentralised identity models.

  • Identify key players and standards in digital identity.

  • Implement a digital identity verification simulation in Python.

  • Develop a framework for blockchain-based KYC implementation.


SECTION 2: WHAT IS DIGITAL IDENTITY?

2.1 Definition

Digital identity is the collection of attributes, credentials, and information that uniquely identifies an individual, organisation, or device in the digital world. In the context of digital finance, identity is critical for KYC, AML, and access control.

2.2 Evolution of Identity Models

text
┌─────────────────────────────────────────────────────────────────────────────┐
│                    EVOLUTION OF IDENTITY MODELS                             │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  1. CENTRALISED IDENTITY                                                   │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │ • Identity controlled by a single authority                         │   │
│  │ • User has no control over data                                     │   │
│  │ • Examples: Government IDs, Facebook login                         │   │
│  │ • Pros: Simple, established                                          │   │
│  │ • Cons: Single point of failure, privacy concerns                  │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  2. FEDERATED IDENTITY                                                      │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │ • Identity shared across multiple organisations                     │   │
│  │ • User has some control                                             │   │
│  │ • Examples: SAML, OAuth, OpenID Connect                            │   │
│  │ • Pros: Convenience, reduced password fatigue                      │   │
│  │ • Cons: Still centralised, data silos                              │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  3. SELF-SOVEREIGN IDENTITY (SSI)                                          │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │ • User owns and controls their identity data                       │   │
│  │ • Decentralised, no single authority                               │   │
│  │ • Examples: DID, Verifiable Credentials                           │   │
│  │ • Pros: User control, privacy, portability                         │   │
│  │ • Cons: Adoption challenges, technical complexity                  │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

SECTION 3: SELF-SOVEREIGN IDENTITY (SSI)

3.1 Core Principles

 
 
Principle Description
Existence Identities exist independently of any external authority.
Control User has full control over their identity and data.
Access User can access their identity at any time.
Transparency Systems and algorithms are open and auditable.
Persistence Identities endure over time.
Portability Identity can be used across platforms.
Interoperability Works across different systems.
Consent User must consent to data sharing.
Minimalisation Only necessary data is shared.
Protection User rights are protected.

3.2 DID Architecture

text
┌─────────────────────────────────────────────────────────────────────────────┐
│                    DID ARCHITECTURE                                         │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    DECENTRALISED IDENTIFIER (DID)                    │   │
│  │  did:method:identifier                                               │   │
│  │  • globally unique                                                   │   │
│  │  • persistent                                                        │   │
│  │  • verifiable                                                        │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    DID DOCUMENT                                      │   │
│  │  • Public keys                                                       │   │
│  │  • Authentication methods                                            │   │
│  │  • Service endpoints                                                 │   │
│  │  • Timestamps                                                        │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    VERIFIABLE CREDENTIAL (VC)                        │   │
│  │  • Issuer DID                                                        │   │
│  │  • Subject DID                                                       │   │
│  │  • Credential claims                                                │   │
│  │  • Cryptographic proof                                              │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    VERIFIABLE PRESENTATION (VP)                      │   │
│  │  • One or more VCs                                                   │   │
│  │  • Holder's proof                                                    │   │
│  │  • Selective disclosure                                              │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

SECTION 4: KYC/AML AND BLOCKCHAIN

4.1 Traditional KYC Challenges

 
 
Challenge Description
Duplication Users repeat KYC across multiple institutions.
Cost High costs for verification and compliance.
Data Breaches Centralised storage of sensitive data.
Slow Process Days to weeks for onboarding.
Exclusion Unbanked populations lack documentation.
Fraud Document forgery and identity theft.

4.2 Blockchain KYC Benefits

text
┌─────────────────────────────────────────────────────────────────────────────┐
│                    BLOCKCHAIN KYC BENEFITS                                  │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    REUSABLE IDENTITY                                │   │
│  │  One KYC verification used across multiple platforms.              │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    USER CONTROL                                      │   │
│  │  Users control their identity data and consent to sharing.          │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    PRIVACY                                            │   │
│  │  Selective disclosure - share only required attributes.             │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    IMMUTABLE AUDIT TRAIL                           │   │
│  │  All consent and verification events are recorded.                 │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    REDUCED COSTS                                    │   │
│  │  Eliminate redundant verification across institutions.             │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

SECTION 5: KEY PLAYERS AND STANDARDS

 
 
Organisation Standard Focus
W3C DID Specification Decentralised Identifiers
W3C Verifiable Credentials Credential data model
DIF Universal Resolver DID resolution
DIF DIDComm DID-based communication
Trust Over IP Governance Framework Interoperable trust
Sovrin Hyperledger Indy Permissioned identity network
uPort Self-sovereign identity Mobile identity wallet

SECTION 6: IMPLEMENTATION IN PYTHON

python
# ===================================================================
# MODULE 3, LESSON 3: DIGITAL IDENTITY AND KYC
# ===================================================================

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

print("="*70)
print("DIGITAL IDENTITY AND KYC – BLOCKCHAIN APPLICATIONS")
print("="*70)

# ----------------------------------------------------------------
# PART A: DIGITAL IDENTITY SIMULATION
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART A: Digital Identity Simulation (Simplified DID)")
print("-"*60)

class DID:
    """
    Simplified implementation of a Decentralised Identifier.
    """
    def __init__(self, method: str = "example", identifier: str = None):
        self.method = method
        self.identifier = identifier or self._generate_id()
        self.keys = {
            'private': self._generate_key(),
            'public': self._generate_key()
        }
        self.did_string = f"did:{method}:{self.identifier}"
        self.created = time.time()
        self.updated = time.time()
    
    def _generate_id(self) -> str:
        """Generate a random identifier."""
        return base64.b64encode(hashlib.sha256(str(time.time()).encode()).digest()).decode()[:16]
    
    def _generate_key(self) -> str:
        """Generate a simulated key."""
        return base64.b64encode(hashlib.sha256(str(random.random()).encode()).digest()).decode()[:32]
    
    def to_did_document(self) -> Dict:
        """Create a DID document."""
        return {
            '@context': 'https://www.w3.org/ns/did/v1',
            'id': self.did_string,
            'verificationMethod': [{
                'id': f'{self.did_string}#keys-1',
                'type': 'Ed25519VerificationKey2020',
                'controller': self.did_string,
                'publicKeyMultibase': self.keys['public']
            }],
            'authentication': [f'{self.did_string}#keys-1'],
            'created': self.created,
            'updated': self.updated
        }
    
    def get_did(self) -> str:
        return self.did_string

class VerifiableCredential:
    """
    Simplified implementation of a Verifiable Credential.
    """
    def __init__(self, issuer: DID, subject: DID, credential_type: str, claims: Dict, expiry_days: int = 365):
        self.issuer = issuer
        self.subject = subject
        self.type = credential_type
        self.claims = claims
        self.issued = time.time()
        self.expiry = self.issued + (expiry_days * 24 * 60 * 60)
        self.id = self._generate_id()
        self.proof = self._sign()
    
    def _generate_id(self) -> str:
        return f"vc-{base64.b64encode(hashlib.sha256(str(time.time()).encode()).digest()).decode()[:16]}"
    
    def _sign(self) -> Dict:
        """Simulate signing the credential."""
        data = f"{self.id}{self.issuer.get_did()}{self.subject.get_did()}{json.dumps(self.claims)}"
        signature = hashlib.sha256(data.encode()).hexdigest()
        return {
            'type': 'Ed25519Signature2020',
            'created': self.issued,
            'verificationMethod': f"{self.issuer.get_did()}#keys-1",
            'proofPurpose': 'assertionMethod',
            'signature': signature
        }
    
    def to_vc_document(self) -> Dict:
        """Create a Verifiable Credential document."""
        return {
            '@context': ['https://www.w3.org/2018/credentials/v1'],
            'id': self.id,
            'type': ['VerifiableCredential', self.type],
            'issuer': self.issuer.get_did(),
            'issuanceDate': self.issued,
            'expirationDate': self.expiry,
            'credentialSubject': {
                'id': self.subject.get_did(),
                **self.claims
            },
            'proof': self.proof
        }
    
    def is_valid(self) -> bool:
        return time.time() < self.expiry
    
    def verify(self) -> bool:
        # Simulate verification
        return self.is_valid()

class IdentityWallet:
    """
    Simulated identity wallet for users.
    """
    def __init__(self, user_id: str):
        self.user_id = user_id
        self.did = DID(method="identity", identifier=user_id)
        self.credentials: List[VerifiableCredential] = []
        self.presentations: List[Dict] = []
    
    def add_credential(self, credential: VerifiableCredential):
        self.credentials.append(credential)
    
    def create_presentation(self, credential_ids: List[str], verifier_did: str) -> Dict:
        """Create a Verifiable Presentation."""
        selected_creds = [c for c in self.credentials if c.id in credential_ids]
        if not selected_creds:
            return {'error': 'No valid credentials found'}
        
        presentation = {
            '@context': ['https://www.w3.org/2018/credentials/v1'],
            'type': ['VerifiablePresentation'],
            'holder': self.did.get_did(),
            'verifier': verifier_did,
            'verifiableCredential': [c.to_vc_document() for c in selected_creds],
            'proof': {
                'type': 'Ed25519Signature2020',
                'created': time.time(),
                'verificationMethod': f"{self.did.get_did()}#keys-1",
                'proofPurpose': 'authentication',
                'challenge': self._generate_challenge()
            }
        }
        self.presentations.append(presentation)
        return presentation
    
    def _generate_challenge(self) -> str:
        return base64.b64encode(hashlib.sha256(str(time.time()).encode()).digest()).decode()[:12]

# Create identities
print("Creating Digital Identities...")
issuer_did = DID(method="government")
alice_did = DID(method="identity", identifier="Alice_001")
bob_did = DID(method="identity", identifier="Bob_001")

print(f"\nIssuer DID: {issuer_did.get_did()}")
print(f"Alice DID: {alice_did.get_did()}")
print(f"Bob DID: {bob_did.get_did()}")

# Create credentials
print("\nCreating Verifiable Credentials...")
alice_credential = VerifiableCredential(
    issuer=issuer_did,
    subject=alice_did,
    credential_type="PassportCredential",
    claims={
        'name': 'Alice Johnson',
        'date_of_birth': '1990-01-15',
        'nationality': 'US',
        'passport_id': 'P12345678'
    }
)

bob_credential = VerifiableCredential(
    issuer=issuer_did,
    subject=bob_did,
    credential_type="DrivingLicenseCredential",
    claims={
        'name': 'Bob Smith',
        'date_of_birth': '1985-07-22',
        'license_id': 'L98765432',
        'license_class': 'C'
    }
)

print(f"Alice Credential: {alice_credential.id}")
print(f"Credential Valid: {alice_credential.is_valid()}")

# ----------------------------------------------------------------
# PART B: KYC VERIFICATION PROCESS
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART B: KYC Verification Process Simulation")
print("-"*60)

class KYCProcess:
    """
    Simulated KYC verification process using blockchain identity.
    """
    def __init__(self, name: str):
        self.name = name
        self.required_credential_types = ['PassportCredential', 'AddressCredential']
        self.verification_log = []
    
    def verify_identity(self, wallet: IdentityWallet, credential_type: str) -> Dict:
        """Verify a specific credential type."""
        # Find matching credential
        matching = [c for c in wallet.credentials if c.type == credential_type]
        if not matching:
            return {'verified': False, 'reason': f'No {credential_type} found'}
        
        credential = matching[0]
        is_valid = credential.verify()
        
        result = {
            'verified': is_valid,
            'credential_type': credential_type,
            'issuer': credential.issuer.get_did(),
            'subject': credential.subject.get_did(),
            'timestamp': time.time()
        }
        
        self.verification_log.append(result)
        return result
    
    def perform_full_kyc(self, wallet: IdentityWallet, user_data: Dict) -> Dict:
        """Perform full KYC verification."""
        results = []
        all_passed = True
        
        print(f"\n=== KYC Verification for {user_data.get('name', 'Unknown')} ===")
        
        for cred_type in self.required_credential_types:
            result = self.verify_identity(wallet, cred_type)
            results.append(result)
            
            # Simulate additional checks
            risk_score = random.uniform(0, 1)
            is_acceptable = risk_score < 0.3
            
            result['additional_check'] = {
                'risk_score': risk_score,
                'passed': is_acceptable
            }
            
            if not result['verified'] or not is_acceptable:
                all_passed = False
            
            status = "✅" if (result['verified'] and is_acceptable) else "❌"
            print(f"  {cred_type}: {status}")
        
        return {
            'passed': all_passed,
            'results': results,
            'timestamp': time.time(),
            'status': 'APPROVED' if all_passed else 'REJECTED'
        }

# Create wallets
alice_wallet = IdentityWallet("Alice_001")
bob_wallet = IdentityWallet("Bob_001")

# Add credentials to wallets
alice_wallet.add_credential(alice_credential)
alice_wallet.add_credential(VerifiableCredential(
    issuer=issuer_did,
    subject=alice_did,
    credential_type="AddressCredential",
    claims={'address': '123 Main St, NY', 'postal_code': '10001'}
))

bob_wallet.add_credential(bob_credential)

# Perform KYC
kyc = KYCProcess("FinTech KYC Service")
alice_result = kyc.perform_full_kyc(alice_wallet, {'name': 'Alice Johnson'})
bob_result = kyc.perform_full_kyc(bob_wallet, {'name': 'Bob Smith'})

print(f"\nKYC Results:")
print(f"  Alice: {alice_result['status']}")
print(f"  Bob: {bob_result['status']}")

# ----------------------------------------------------------------
# PART C: KYC COMPLIANCE METRICS
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART C: KYC Compliance Metrics")
print("-"*60)

# Simulate KYC data
kyc_metrics = pd.DataFrame({
    'Metric': [
        'Average Onboarding Time',
        'KYC Verification Cost',
        'Fraud Detection Rate',
        'False Positive Rate',
        'Customer Satisfaction Score',
        'Data Breach Incidents',
        'Regulatory Compliance Score'
    ],
    'Traditional': [
        '7-14 days',
        '$50-100',
        '70%',
        '15%',
        '3.5/5',
        'High',
        'Medium'
    ],
    'Blockchain-Based': [
        '1-2 hours',
        '$5-15',
        '92%',
        '5%',
        '4.5/5',
        'Low',
        'High'
    ],
    'Improvement': [
        '90% reduction',
        '80% reduction',
        '31% improvement',
        '66% reduction',
        '29% improvement',
        'Significant reduction',
        'Improved'
    ]
})

print(kyc_metrics.to_string(index=False))

# Visualise KYC metrics comparison
fig, axes = plt.subplots(1, 2, figsize=(14, 5))

# 1. Cost and Time comparison
ax1 = axes[0]
categories = ['Onboarding Time (days)', 'Verification Cost ($)']
traditional_values = [10.5, 75]
blockchain_values = [1.5, 10]
x = np.arange(len(categories))
width = 0.35

ax1.bar(x - width/2, traditional_values, width, label='Traditional', color='red', alpha=0.7)
ax1.bar(x + width/2, blockchain_values, width, label='Blockchain', color='green', alpha=0.7)
ax1.set_xticks(x)
ax1.set_xticklabels(categories)
ax1.set_ylabel('Value')
ax1.set_title('KYC Efficiency Improvement')
ax1.legend()
ax1.grid(True, alpha=0.3)

# 2. Performance metrics
ax2 = axes[1]
performance = ['Fraud Detection', 'False Positive Rate', 'Satisfaction']
traditional_pct = [70, 15, 70]  # 3.5/5 = 70%
blockchain_pct = [92, 5, 90]    # 4.5/5 = 90%

x = np.arange(len(performance))
ax2.bar(x - width/2, traditional_pct, width, label='Traditional', color='red', alpha=0.7)
ax2.bar(x + width/2, blockchain_pct, width, label='Blockchain', color='green', alpha=0.7)
ax2.set_xticks(x)
ax2.set_xticklabels(performance)
ax2.set_ylabel('Percentage (%)')
ax2.set_title('KYC Performance Metrics')
ax2.legend()
ax2.grid(True, alpha=0.3)

plt.tight_layout()
plt.savefig('kyc_comparison.png', dpi=300, bbox_inches='tight')
plt.show()
print("KYC comparison chart saved as 'kyc_comparison.png'")

# ----------------------------------------------------------------
# PART D: IDENTITY MANAGEMENT FRAMEWORK
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART D: Identity Management Framework")
print("-"*60)

identity_framework = {
    "Principles": {
        "User Control": "Users own and control their identity data",
        "Privacy by Design": "Privacy embedded in the system",
        "Interoperability": "Works across platforms and jurisdictions",
        "Transparency": "Open and auditable processes"
    },
    "Components": {
        "DID Registry": "On-chain registry for identifiers",
        "Wallet": "Secure storage for identity data",
        "Verifier": "Verification of credentials",
        "Issuer": "Trusted credential issuer"
    },
    "Standards": {
        "DID": "W3C DID Specification",
        "VC": "W3C Verifiable Credentials",
        "DIDComm": "DID Communication",
        "KERI": "Key Event Receipt Infrastructure"
    },
    "Use Cases": {
        "Financial Services": "KYC/AML, onboarding",
        "Healthcare": "Patient records, consent",
        "Government": "E-government, voting",
        "Travel": "Passports, visas"
    }
}

for category, details in identity_framework.items():
    print(f"\n{category.upper()}:")
    for key, value in details.items():
        print(f"  • {key}: {value}")

# ----------------------------------------------------------------
# PART E: SUMMARY AND RECOMMENDATIONS
# ----------------------------------------------------------------

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

print("""
Digital Identity and KYC with Blockchain – Key Takeaways:

1. Digital identity has evolved from centralised to self-sovereign models.
2. SSI gives users control over their identity and data.
3. DIDs are persistent, verifiable identifiers independent of any authority.
4. Verifiable Credentials enable secure, verifiable claims.
5. Blockchain KYC reduces costs, time, and fraud while improving privacy.
6. Key standards: W3C DID, VC, DIF protocols.
7. Blockchain KYC enables reusable identity across multiple platforms.

Recommendations:
  - Implement SSI principles in identity solutions.
  - Use established standards (W3C DID, VC).
  - Ensure regulatory compliance (GDPR, eIDAS).
  - Design for interoperability across platforms.
  - Educate users on identity control and privacy.
  - Start with a focused use case (e.g., KYC).
  - Build governance for identity verification.
""")

print("="*70)
print("END OF LESSON 3 – MODULE 3")
print("="*70)