# GPN Payment Flow

## Overview

The DBIS Global Payments Network (GPN) processes payments through a three-layer architecture: Sovereign Access Layer, Global Switching Layer, and Finality Layer. This flow documents the complete payment routing and settlement process.

## Prerequisites

- Source and destination accounts exist and are active
- Sufficient balance in source account
- Valid SDIP (Sovereign Digital Identity Passport) for authentication
- GPN service is operational
- ISO 20022 message format compliance

## Visual Flow Diagram

```mermaid
sequenceDiagram
    participant PI as Payment Initiator
    participant L1 as Layer 1: Sovereign Access
    participant L2 as Layer 2: Global Switching
    participant L3 as Layer 3: Finality
    participant SCB as SCB Ledger
    participant DBIS as DBIS Ledger
    
    PI->>L1: Payment Request (PACS.008)
    Note over L1: SDIP Authentication<br/>Zero-trust verify<br/>Traffic segmentation
    L1->>L1: Validate SDIP
    L1->>L1: Zero-trust check
    L1->>L2: Authenticated Request
    
    Note over L2: FX cost optimization<br/>Liquidity check<br/>SRI risk weighting<br/>Route calculation
    L2->>L2: Calculate optimal route
    L2->>L2: Check liquidity
    L2->>L2: Apply SRI weighting
    L2->>L3: Route Selected
    
    Note over L3: Hash-lock creation<br/>Dual-ledger posting<br/>Hash-lock verification
    L3->>L3: Create hash-lock
    L3->>SCB: Post to SCB Ledger
    L3->>DBIS: Post to DBIS Ledger
    SCB-->>L3: Confirmation
    DBIS-->>L3: Confirmation
    L3->>L3: Verify hash-lock
    L3->>PI: Finality Confirmed
```

**ASCII Diagram (Legacy)**:
```
┌─────────────┐
│   Payment   │
│  Initiator  │
└──────┬──────┘
       │
       │ 1. Payment Request
       │    (PACS.008)
       ▼
┌─────────────────────────┐
│  Layer 1: Sovereign      │
│  Access Layer           │
│  - SDIP Authentication   │
│  - Zero-trust verify    │
│  - Traffic segmentation │
└──────┬──────────────────┘
       │
       │ 2. Authenticated
       ▼
┌─────────────────────────┐
│  Layer 2: Global        │
│  Switching Layer        │
│  - FX cost optimization  │
│  - Liquidity check      │
│  - SRI risk weighting   │
│  - Route calculation    │
└──────┬──────────────────┘
       │
       │ 3. Route Selected
       ▼
┌─────────────────────────┐
│  Layer 3: Finality      │
│  Layer                   │
│  - Hash-lock creation   │
│  - SCB ledger post       │
│  - DBIS ledger post      │
│  - Hash-lock verify     │
└──────┬──────────────────┘
       │
       │ 4. Finality Confirmed
       ▼
┌─────────────┐
│  Payment    │
│  Settled    │
└─────────────┘
```

## Step-by-Step Process

### Step 1: Payment Initiation
1. Payment initiator submits payment request via API or ISO 20022 message (PACS.008)
2. GPN message handler receives and validates message format
3. Extract payment details:
   - Source account (debtorAccount)
   - Destination account (creditorAccount)
   - Amount and currency
   - Payment priority
   - Reference information

**Code Reference**: `src/core/payments/payment.service.ts:18-73`

### Step 2: Layer 1 - Sovereign Access Authentication
1. Extract SDIP from request headers or message
2. Verify SDIP signature using sovereign identity service
3. Validate sovereign bank ID matches SDIP
4. Check zero-trust authentication:
   - Verify request signature
   - Validate timestamp (prevent replay attacks)
   - Check access permissions
5. Segment traffic by sovereign identity

**Code Reference**: `src/integration/api-gateway/middleware/auth.middleware.ts`

### Step 3: Account Validation
1. Lookup source account (debtorAccount) by account number
2. Lookup destination account (creditorAccount) by account number
3. Verify both accounts exist and are active
4. Check source account balance:
   - Calculate available balance
   - Verify sufficient funds for payment amount
   - Consider any pending holds or reserves
5. If insufficient balance, return error and terminate flow

**Code Reference**: `src/core/accounts/account.service.ts`

### Step 4: Layer 2 - Global Switching & Routing
1. Calculate optimal route using:
   - FX cost optimization
   - Liquidity availability check
   - SRI-based risk weighting
   - Settlement mode (RTGS vs DNS)
2. Determine settlement mode based on priority:
   - RTGS for urgent/high-priority payments
   - DNS for normal/deferred payments
3. Select routing path:
   - Direct SCB-to-SCB if same currency
   - Via GSS if cross-currency
   - Via SSU if optimal for cross-border
4. Create payment routing record

**Code Reference**: `src/core/settlement/sire/sire-routing.service.ts`

### Step 5: Layer 3 - Finality & Settlement
1. Create hash-lock for atomic settlement:
   - Generate commitment hash
   - Store hash-lock record
2. Post to SCB sovereign ledger:
   - Create debit entry on source account
   - Create credit entry on destination account
   - Generate sovereign ledger hash
3. Post to DBIS master ledger:
   - Create corresponding entries
   - Generate DBIS ledger hash
4. Verify hash-lock match:
   - Compare sovereign and DBIS hashes
   - Verify dual-ledger commit
5. Mark payment as settled

**Code Reference**: 
- `src/core/settlement/gss/gss-master-ledger.service.ts:35-96`
- `src/core/ledger/ledger-lifecycle.service.ts:44-139`

### Step 6: Confirmation & Notification
1. Generate payment status report (PACS.002)
2. Send confirmation to payment initiator
3. Notify destination bank (if different sovereign)
4. Update payment status in database
5. Log settlement event

## Error Handling

### Error: Account Not Found
- **Detection**: Account lookup returns null
- **Action**: Return error code `NOT_FOUND`
- **Recovery**: Terminate flow, notify initiator

### Error: Insufficient Balance
- **Detection**: Available balance < payment amount
- **Action**: Return error code `VALIDATION_ERROR`
- **Recovery**: Terminate flow, suggest alternative payment methods

### Error: Authentication Failure
- **Detection**: SDIP verification fails
- **Action**: Return error code `UNAUTHORIZED`
- **Recovery**: Terminate flow, log security event

### Error: Routing Failure
- **Detection**: No valid route found
- **Action**: Return error code `ROUTING_ERROR`
- **Recovery**: Retry with alternative routing, escalate if persistent

### Error: Dual-Ledger Commit Failure
- **Detection**: Hash-lock verification fails
- **Action**: Rollback both ledger entries
- **Recovery**: 
  - Mark payment as failed
  - Create reconciliation record
  - Notify operations team

## Integration Points

### Related Services
- **Payment Service**: `src/core/payments/payment.service.ts`
- **Account Service**: `src/core/accounts/account.service.ts`
- **Ledger Service**: `src/core/ledger/ledger.service.ts`
- **GSS Master Ledger**: `src/core/settlement/gss/gss-master-ledger.service.ts`
- **SIRE Routing**: `src/core/settlement/sire/sire-routing.service.ts`
- **Identity Service**: `src/core/cbdc/interoperability/cim-identity.service.ts`

### API Endpoints
- `POST /api/v1/gpn/authenticate` - Layer 1 authentication
- `POST /api/v1/gpn/route` - Layer 2 routing
- `POST /api/v1/gpn/finality` - Layer 3 finality verification
- `POST /api/v1/gpn/message/pacs008` - ISO 20022 message handling

### Database Models
- `GpnPayment` - Payment routing records
- `GpnRoute` - Routing paths with cost/risk metrics
- `GpnSettlementLock` - Hash-lock records for finality

## Performance Metrics

- **Layer 1 (Authentication)**: < 50ms target
- **Layer 2 (Routing)**: < 100ms target
- **Layer 3 (Finality)**: < 200ms target
- **Total End-to-End**: < 350ms target
- **Throughput**: 10,000+ payments/second per node
- **Availability**: 99.99% uptime target

## Security Considerations

### Authentication Checkpoints
1. SDIP signature verification (Layer 1)
2. Request signature validation
3. Timestamp verification (replay attack prevention)
4. Access permission checks

### Authorization
- Sovereign bank must have active status
- Account must have transfer permissions
- Payment amount within policy limits

### Data Protection
- All messages encrypted in transit (TLS 1.3)
- Sensitive data encrypted at rest
- Audit logging for all operations

## Testing Scenarios

### Happy Path
1. Valid payment request with sufficient balance
2. Successful authentication
3. Successful routing
4. Successful dual-ledger commit
5. Payment settled within SLA

### Error Scenarios
1. Invalid SDIP signature
2. Account not found
3. Insufficient balance
4. Routing failure
5. Dual-ledger commit failure
6. Network timeout

### Edge Cases
1. Concurrent payments to same account
2. Maximum payment amount
3. Minimum payment amount
4. Cross-currency payments
5. Offline destination bank

## Recommendations

### Error Handling Strategies

**Priority: High**

1. **Retry Mechanisms**
   - **Description**: Implement intelligent retry logic for transient failures
   - **Implementation**: Use exponential backoff, maximum retry limits, circuit breaker pattern
   - **Impact**: Improves system resilience and reduces manual intervention
   - **Dependencies**: Retry middleware, circuit breaker library

2. **Idempotency Keys**
   - **Description**: Ensure payment requests are idempotent
   - **Implementation**: Generate unique idempotency keys, check for duplicate requests, return same response for duplicates
   - **Impact**: Prevents duplicate payments and enables safe retries
   - **Dependencies**: Idempotency key storage, request deduplication service

3. **Compensation Transactions**
   - **Description**: Implement compensation for failed payments
   - **Implementation**: Track payment state, implement rollback procedures, notify parties of failures
   - **Impact**: Ensures financial consistency and proper error recovery
   - **Dependencies**: State tracking system, compensation service

### Performance Optimization

**Priority: High**

1. **Payment Batching**
   - **Description**: Batch multiple payments for efficiency
   - **Implementation**: Collect payments in time windows, batch process, optimize database writes
   - **Impact**: Reduces database load and improves throughput
   - **Dependencies**: Batching service, batch processing framework

2. **Caching Strategy**
   - **Description**: Cache frequently accessed data
   - **Implementation**: Cache account balances, FX rates, routing tables, use TTL-based invalidation
   - **Impact**: Reduces database queries and improves response times
   - **Dependencies**: Caching infrastructure (Redis), cache invalidation service

3. **Async Processing**
   - **Description**: Process non-critical operations asynchronously
   - **Implementation**: Use message queues for notifications, reporting, audit logging
   - **Impact**: Improves API response times and system scalability
   - **Dependencies**: Message queue infrastructure (Kafka, RabbitMQ)

### Security Hardening

**Priority: Critical**

1. **Request Signature Verification**
   - **Description**: Verify all payment requests are properly signed
   - **Implementation**: Use HSM-backed signatures, verify signatures on all requests, reject unsigned requests
   - **Impact**: Prevents unauthorized payment requests
   - **Dependencies**: HSM infrastructure, signature verification service

2. **Rate Limiting**
   - **Description**: Implement per-sovereign rate limiting
   - **Implementation**: Track request rates, enforce limits, alert on violations
   - **Impact**: Prevents abuse and ensures fair resource allocation
   - **Dependencies**: Rate limiting middleware, monitoring system

3. **Audit Logging**
   - **Description**: Comprehensive audit trail for all payments
   - **Implementation**: Log all payment operations, store in tamper-proof storage, enable audit queries
   - **Impact**: Enables compliance and forensic analysis
   - **Dependencies**: Audit logging service, secure storage

### Monitoring Points

**Priority: High**

1. **Payment Latency Monitoring**
   - Monitor time at each layer (L1, L2, L3)
   - Alert on SLA violations
   - Track p50, p95, p99 latencies

2. **Error Rate Monitoring**
   - Track error rates by error type
   - Monitor authentication failures
   - Alert on error rate spikes

3. **Throughput Monitoring**
   - Track payments per second
   - Monitor queue depths
   - Alert on capacity issues

### Testing Approaches

**Priority: Medium**

1. **Load Testing**
   - Test system under expected load
   - Identify bottlenecks
   - Validate SLA compliance

2. **Chaos Engineering**
   - Test failure scenarios
   - Validate failover mechanisms
   - Ensure system resilience

3. **Security Testing**
   - Penetration testing
   - Fuzz testing
   - Vulnerability scanning

---

**Related Flows**:
- [GSS Settlement Flow](./gss-settlement-flow.md)
- [M-RTGS Settlement Flow](./m-rtgs-settlement-flow.md)
- [Atomic Settlement Flow](./atomic-settlement-flow.md)

