# AS4 Settlement Setup Guide

**Date**: 2026-01-19  
**Version**: 1.0.0

---

## Prerequisites

- Node.js 18+
- PostgreSQL 14+
- Redis 7+ (for nonce tracking)
- Prisma CLI
- Access to DBIS database

---

## Step 1: Database Migration

Run the Prisma migration to create the AS4 settlement tables:

```bash
cd dbis_core
npx prisma generate
npx prisma migrate deploy
```

Or for development:

```bash
npx prisma migrate dev --name add_as4_settlement_models
```

---

## Step 2: Environment Variables

Add the following environment variables to your `.env` file:

```env
# AS4 Gateway Configuration
AS4_BASE_URL=https://as4.dbis.org
AS4_GATEWAY_PORT=8443

# Certificate Configuration
AS4_TLS_CERT_PATH=/path/to/tls/cert.pem
AS4_TLS_KEY_PATH=/path/to/tls/key.pem
AS4_SIGNING_CERT_PATH=/path/to/signing/cert.pem
AS4_SIGNING_KEY_PATH=/path/to/signing/key.pem

# HSM Configuration (if using HSM)
HSM_ENABLED=true
HSM_PROVIDER=softhsm
HSM_SLOT=0
HSM_PIN=your-pin

# Redis Configuration (for nonce tracking)
REDIS_URL=redis://localhost:6379
AS4_NONCE_TTL=300  # 5 minutes in seconds

# ChainID 138 Configuration
CHAIN138_RPC_URL=http://192.168.11.250:8545
CHAIN138_ANCHOR_INTERVAL=3600  # 1 hour in seconds

# Compliance Configuration
SANCTIONS_SCREENING_ENABLED=true
AML_CHECKS_ENABLED=true
```

---

## Step 3: Seed Marketplace Offering

Run the seed script to add the AS4 Settlement offering to the marketplace:

```bash
npx ts-node scripts/seed-as4-settlement-marketplace-offering.ts
```

---

## Step 4: Verify Routes

The AS4 routes are automatically registered in `src/integration/api-gateway/app.ts`:

- `/api/v1/as4/gateway/*` - AS4 Gateway endpoints
- `/api/v1/as4/directory/*` - Member Directory endpoints
- `/api/v1/as4/settlement/*` - Settlement endpoints

---

## Step 5: Certificate Setup

### For DBIS (Settlement Institution)

1. Generate TLS certificate:
```bash
openssl req -x509 -newkey rsa:2048 -keyout as4-tls-key.pem -out as4-tls-cert.pem -days 365 -nodes
```

2. Generate signing certificate:
```bash
openssl req -x509 -newkey rsa:2048 -keyout as4-signing-key.pem -out as4-signing-cert.pem -days 365 -nodes
```

3. Calculate fingerprints:
```bash
openssl x509 -fingerprint -sha256 -noout -in as4-tls-cert.pem
openssl x509 -fingerprint -sha256 -noout -in as4-signing-cert.pem
```

4. Store certificates securely (HSM recommended for production)

### For Members

Members will register their certificates via the Member Directory API during onboarding.

---

## Step 6: Testing

### Health Check

```bash
curl http://localhost:3000/health
```

### Register Test Member

```bash
curl -X POST http://localhost:3000/api/v1/as4/directory/members \
  -H "Content-Type: application/json" \
  -d '{
    "memberId": "TEST-MEMBER-001",
    "organizationName": "Test Bank",
    "as4EndpointUrl": "https://test-bank.example.com/as4",
    "tlsCertFingerprint": "AA:BB:CC:DD:EE:FF",
    "allowedMessageTypes": ["DBIS.SI.202", "DBIS.SI.202COV"]
  }'
```

### Submit Test Instruction

```bash
curl -X POST http://localhost:3000/api/v1/as4/settlement/instructions \
  -H "Content-Type: application/json" \
  -d '{
    "fromMemberId": "TEST-MEMBER-001",
    "payloadHash": "abc123",
    "message": {
      "MessageId": "MSG-001",
      "BusinessType": "DBIS.SI.202",
      "CreatedAt": "2026-01-19T12:00:00Z",
      "FromMemberId": "TEST-MEMBER-001",
      "ToMemberId": "DBIS",
      "Instr": {
        "InstrId": "INSTR-001",
        "ValueDate": "2026-01-20",
        "Currency": "USD",
        "Amount": "1000.00",
        "DebtorAccount": "MSA:TEST-MEMBER-001:USD",
        "CreditorAccount": "MSA:TEST-MEMBER-002:USD"
      }
    }
  }'
```

---

## Step 7: Production Deployment

### High Availability

- Deploy multiple AS4 gateway instances behind a load balancer
- Use shared Redis cluster for nonce tracking
- Configure database replication

### Monitoring

- Set up Prometheus metrics
- Configure alerting for:
  - Certificate expiration warnings
  - Failed instruction rate
  - System availability
  - Message processing latency

### Security

- Enable HSM for key management
- Configure firewall rules
- Set up DDoS protection
- Enable audit logging

---

## Troubleshooting

### Database Connection Issues

Check database connectivity:
```bash
psql -h 192.168.11.105 -U dbis_user -d dbis_core -c "SELECT 1"
```

### Certificate Issues

Verify certificate format:
```bash
openssl x509 -in cert.pem -text -noout
```

### Redis Connection Issues

Test Redis connectivity:
```bash
redis-cli -h localhost -p 6379 ping
```

---

## Support

For issues or questions:
- Documentation: `/docs/settlement/as4/`
- Operational Runbooks: `/docs/settlement/as4/OPERATIONAL_RUNBOOKS.md`
- Incident Response: `/docs/settlement/as4/INCIDENT_RESPONSE.md`

---

**End of Setup Guide**
