# Deployment Guide - RPC Translator Service

This guide covers deploying the RPC Translator service on Proxmox VMIDs 2400-2402 for ChainID 138.

## Prerequisites

1. **VMIDs 2400-2402** - RPC nodes with Besu already running
2. **Redis VMID 106** - IP: 192.168.11.110 (nonce management)
3. **Web3Signer VMID 107** - IP: 192.168.11.111 (transaction signing)
4. **Vault VMID 108** - IP: 192.168.11.112 (configuration management)

## Deployment Steps

### 1. Deploy Supporting Services

#### Option A: Automated Deployment (Recommended)

Use the deployment script to create LXC containers:

```bash
# Verify node is ready
cd rpc-translator-138
./verify-node-ready.sh r630-01

# Deploy all supporting services
./deploy-supporting-services.sh r630-01
```

#### Option B: Manual Deployment

##### Redis VMID 106 (192.168.11.110)

Create LXC container and configure Redis:

```bash
# On Proxmox host, create container
pct create 106 local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst \
  --hostname redis-rpc-translator \
  --cores 2 --memory 512 --swap 512 \
  --storage local-lvm --rootfs local-lvm:10 \
  --net0 name=eth0,bridge=vmbr0,ip=192.168.11.110/24,gw=192.168.11.1 \
  --onboot 1 --unprivileged 0

# Start container
pct start 106

# Enter container
pct enter 106

# Install Redis
apt-get update
apt-get install -y redis-server

# Configure Redis (optional: add password, bind to specific IP)
nano /etc/redis/redis.conf
# Set: bind 192.168.11.110 (translator VMIPs only: 240-242)
# Set: requirepass <password> (optional, recommended for production)

systemctl enable redis-server
systemctl start redis-server
```

##### Web3Signer VMID 107 (192.168.11.111)

Create LXC container and configure Web3Signer:

```bash
# On Proxmox host, create container
pct create 107 local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst \
  --hostname web3signer-rpc-translator \
  --cores 2 --memory 2048 --swap 2048 \
  --storage local-lvm --rootfs local-lvm:20 \
  --net0 name=eth0,bridge=vmbr0,ip=192.168.11.111/24,gw=192.168.11.1 \
  --onboot 1 --unprivileged 0

# Start container
pct start 107

# Enter container
pct enter 107

# Install Java (required for Web3Signer)
apt-get update
apt-get install -y openjdk-17-jre-headless wget

# Download Web3Signer
wget https://artifacts.consensys.net/web3signer/web3signer-23.10.0/web3signer-23.10.0.tar.gz
tar -xzf web3signer-23.10.0.tar.gz
cd web3signer-23.10.0

# Configure Web3Signer
# See Web3Signer documentation for key configuration
# Keys should be loaded from Vault or secure storage
# Configure to listen on 192.168.11.111:9000
# Restrict access to translator VMIPs only (240-242)
```

##### Vault VMID 108 (192.168.11.112)

Create LXC container and configure HashiCorp Vault:

```bash
# On Proxmox host, create container
pct create 108 local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst \
  --hostname vault-rpc-translator \
  --cores 2 --memory 2048 --swap 2048 \
  --storage local-lvm --rootfs local-lvm:20 \
  --net0 name=eth0,bridge=vmbr0,ip=192.168.11.112/24,gw=192.168.11.1 \
  --onboot 1 --unprivileged 0

# Start container
pct start 108

# Enter container
pct enter 108

# Install Vault
apt-get update
apt-get install -y unzip wget
wget https://releases.hashicorp.com/vault/1.15.0/vault_1.15.0_linux_amd64.zip
unzip vault_1.15.0_linux_amd64.zip
mv vault /usr/local/bin/
chmod +x /usr/local/bin/vault

# Initialize Vault (production mode with TLS recommended)
# For development/testing:
vault server -dev -dev-listen-address="192.168.11.112:8200"
# Note: Use proper production configuration with TLS in production

# Create AppRole for translator
vault auth enable approle
vault write auth/approle/role/translator \
  token_policies="translator-policy" \
  bind_secret_id=true

# Create policy
vault policy write translator-policy - <<EOF
path "secret/data/chain138/translator" {
  capabilities = ["read"]
}
EOF

# Store translator configuration
vault kv put secret/chain138/translator \
  walletAllowlist="0x...,0x...,0x..." \
  maxGasLimit="30000000" \
  maxGasPriceWei="100000000000" \
  minGasPriceWei="1000000000"
```

### 2. Deploy Translator on VMIDs 2400-2402

For each VMID (2400, 2401, 2402):

#### 2.1 Install Node.js

```bash
# Install Node.js 20 LTS
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt-get install -y nodejs

# Install pnpm
npm install -g pnpm

# Verify
node --version  # Should be v20.x.x
pnpm --version
```

#### 2.2 Deploy Application

```bash
# Create application directory
mkdir -p /opt/rpc-translator-138
cd /opt/rpc-translator-138

# Copy application files (from your deployment method)
# Option 1: Git clone
git clone <repository-url> .
cd rpc-translator-138

# Option 2: Copy files via scp/rsync
# scp -r rpc-translator-138/ user@vmid:/opt/rpc-translator-138/

# Install dependencies
pnpm install --prod
# or: npm install --production

# Build
pnpm run build
# or: npm run build
```

#### 2.3 Configure Environment

```bash
# Create .env file from template
cp /opt/rpc-translator-138/env.template /opt/rpc-translator-138/.env
nano /opt/rpc-translator-138/.env
```

Configure for each VMID (adjust IPs as needed):

```bash
# Server Configuration
HTTP_PORT=9545
WS_PORT=9546
NODE_ENV=production

# Besu Upstream (local)
BESU_HTTP_URLS=http://127.0.0.1:8545
BESU_WS_URLS=ws://127.0.0.1:8546
CHAIN_ID=138

# Web3Signer (VMID 107)
WEB3SIGNER_URL=http://192.168.11.111:9000
WEB3SIGNER_TIMEOUT=5000

# Redis (VMID 106)
REDIS_HOST=192.168.11.110
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DB=0
REDIS_KEY_PREFIX=rpc-translator:138

# Vault (VMID 108)
VAULT_ADDR=http://192.168.11.112:8200
VAULT_ROLE_ID=<from-vault-output>
VAULT_SECRET_ID=<from-vault-output>
VAULT_PATH_TRANSLATOR_CONFIG=secret/data/chain138/translator
```

#### 2.4 Create Systemd Service

```bash
nano /etc/systemd/system/rpc-translator-138.service
```

```ini
[Unit]
Description=RPC Translator Service for ChainID 138
After=network.target besu-rpc.service
Wants=besu-rpc.service

[Service]
Type=simple
User=root
WorkingDirectory=/opt/rpc-translator-138
Environment=NODE_ENV=production
ExecStart=/usr/bin/node dist/main.js
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
```

Enable and start:

```bash
systemctl daemon-reload
systemctl enable rpc-translator-138.service
systemctl start rpc-translator-138.service
systemctl status rpc-translator-138.service
```

#### 2.5 Verify Service

```bash
# Check logs
journalctl -u rpc-translator-138.service -f

# Test HTTP endpoint
curl -X POST http://127.0.0.1:9545 \
  -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}'

# Test health endpoint
curl http://127.0.0.1:9545/health
```

### 3. Update Edge Routing

Update your existing edge routing (Cloudflare Tunnel, Nginx, etc.) to forward traffic from external ports to translator ports:

#### Cloudflare Tunnel

Update tunnel configuration to forward:
- External `:8545` → `2400:9545, 2401:9545, 2402:9545`
- External `:8546` → `2400:9546, 2401:9546, 2402:9546`

#### Nginx (if using central Nginx Proxy Manager)

Update upstream configuration to point to translator ports instead of Besu ports.

### 4. Validation Tests

#### Test WebSocket Subscriptions

```javascript
const ws = new WebSocket('wss://your-rpc-endpoint:8546');
ws.on('open', () => {
  ws.send(JSON.stringify({
    jsonrpc: '2.0',
    method: 'eth_subscribe',
    params: ['newHeads'],
    id: 1
  }));
});
ws.on('message', (data) => {
  console.log('Received:', JSON.parse(data.toString()));
});
```

#### Test Transaction Sending

```javascript
const response = await fetch('https://your-rpc-endpoint:8545', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    jsonrpc: '2.0',
    method: 'eth_sendTransaction',
    params: [{
      from: '0x...', // Must be in allowlist
      to: '0x...',
      value: '0x0',
      gas: '0x5208',
    }],
    id: 1
  })
});
const result = await response.json();
console.log('Transaction hash:', result.result);
```

#### Test Nonce Management

Send 10 concurrent transactions from the same address and verify they have sequential nonces.

#### Test Failover

Stop one translator instance and verify traffic routes to remaining instances.

## Troubleshooting

### Service Won't Start

1. Check logs: `journalctl -u rpc-translator-138.service -n 100`
2. Verify Node.js is installed: `node --version`
3. Verify dependencies: `cd /opt/rpc-translator-138 && npm list`
4. Check port availability: `netstat -tulpn | grep 9545`

### Redis Connection Issues

1. Test Redis connectivity: `redis-cli -h 192.168.11.110 ping` (VMID 106)
2. Check firewall rules
3. Verify Redis configuration allows connections from translator IPs

### Web3Signer Connection Issues

1. Test Web3Signer: `curl http://192.168.11.111:9000/upcheck` (VMID 107)
2. Verify Web3Signer has keys loaded
3. Check firewall rules

### Vault Connection Issues

1. Test Vault: `vault status -address=http://192.168.11.112:8200` (VMID 108)
2. Verify AppRole credentials are correct
3. Check vault policy permissions

### Transaction Failures

1. Verify wallet address is in allowlist
2. Check gas/fee limits in policy
3. Verify Web3Signer has the key for the wallet address
4. Check Besu logs for transaction rejection reasons

## Maintenance

### Updating the Service

```bash
cd /opt/rpc-translator-138
git pull  # or copy new files
pnpm install --prod  # or: npm install --production
pnpm run build  # or: npm run build
systemctl restart rpc-translator-138.service
```

### Clearing Nonce Cache

If nonces become stuck:

```bash
redis-cli -h 192.168.11.110  # VMID 106
DEL rpc-translator:138:nonce:138:<address>
```

### Monitoring

Monitor service health via:
- Systemd status: `systemctl status rpc-translator-138.service`
- Health endpoint: `curl http://localhost:9545/health`
- Logs: `journalctl -u rpc-translator-138.service -f`

## Security Considerations

1. **Firewall Rules**: Restrict Redis, Web3Signer, and Vault to only accept connections from translator VMIPs
2. **TLS**: Use TLS for Vault in production (dev mode is for testing only)
3. **Secrets**: Store Vault credentials securely (consider using Vault's AppRole with secret rotation)
4. **Key Management**: Web3Signer keys should be loaded from Vault or secure storage
5. **Rate Limiting**: Consider adding rate limiting at the edge (Cloudflare, Nginx)

## Next Steps

- Set up Prometheus metrics (Phase 2)
- Configure mTLS/IP allowlisting (Phase 2)
- Implement key rotation procedures
- Set up automated testing
- Configure alerting and monitoring
