# Superball Thrower Daemon

A standalone Node.js daemon implementation of the Superball Thrower functionality, extracted from the web-based implementation. This daemon runs as a system service and provides privacy-focused routing for the Superball protocol.

## Features

- **Complete Superball Protocol Support**: Implements SUP-01 through SUP-06
- **NIP-44 Encryption**: Secure event routing with NOSTR encryption standards
- **NIP-65 Relay Management**: Automatic relay list publishing and management
- **Event Queue Processing**: Delayed processing with routing instructions
- **Relay Authentication Testing**: Automatic detection of read/write capabilities
- **Thrower Information Publishing**: SUP-06 compliant thrower announcements
- **Maximum Delay Validation**: Security feature to prevent excessive delays (default: 86460 seconds = 1 day + 60s)
- **Systemd Integration**: Runs as a secure system service
- **Comprehensive Logging**: Detailed operation logs for monitoring

## Quick Start

1. **Install the daemon:**
   ```bash
   chmod +x install.sh
   ./install.sh
   ```

2. **Configure your thrower:**
   ```bash
   sudo nano /etc/superball/config.json
   ```

3. **Start the service:**
   ```bash
   sudo systemctl enable superball-thrower
   sudo systemctl start superball-thrower
   ```

4. **Monitor the service:**
   ```bash
   sudo systemctl status superball-thrower
   sudo journalctl -u superball-thrower -f
   ```

## Configuration

The daemon uses `/etc/superball/config.json` for configuration. Key settings include:

### Required Settings
- `privateKey`: Your thrower's private key (hex format)
- `relays`: Array of relay configurations with read/write permissions

### Optional Settings
- `throwerInfo`: Thrower Information Document settings (SUP-06)
- `maxDelay`: Maximum delay in seconds for routing instructions (default: 86460 = 1 day + 60s)
- `refreshRate`: How often to republish thrower info in seconds (default: 300)

### Example Configuration
```json
{
  "thrower": {
    "privateKey": "your-private-key-in-hex",
    "name": "My Superball Thrower",
    "description": "A privacy-focused Superball routing node",
    "maxDelay": 86460,
    "refreshRate": 300
  },
  "relays": [
    {
      "url": "wss://relay.laantungir.net",
      "read": true,
      "write": true
    },
    {
      "url": "wss://relay.damus.io",
      "read": true,
      "write": false
    }
  ],
  "daemon": {
    "logLevel": "info",
    "maxQueueSize": 1000,
    "autoStart": false
  }
}
```

## Architecture

### Core Components

1. **Event Monitor**: Subscribes to kind 22222 events across configured relays
2. **Decryption Engine**: Handles NIP-44 decryption of routing instructions
3. **Queue Processor**: Manages delayed event processing
4. **Relay Manager**: Tests and manages relay authentication capabilities
5. **Publisher**: Handles event forwarding and final posting

### Protocol Implementation

- **SUP-01**: Basic routing protocol support
- **SUP-02**: Event queuing and delayed processing
- **SUP-03**: Padding layer handling for privacy
- **SUP-04**: Relay authentication and capability detection
- **SUP-05**: Event validation and security checks
- **SUP-06**: Thrower Information Document publishing

### Security Features

- **Maximum Delay Validation**: Prevents excessive routing delays (default: 86460 seconds)
- **Event Deduplication**: Prevents processing the same event multiple times
- **Relay Authentication**: Only uses write-capable relays for publishing
- **Private Key Security**: Configuration file secured with proper permissions

## File Structure

```
thrower_daemon/
├── daemon.js              # Main daemon implementation
├── package.json           # Node.js dependencies
├── config.json           # Example configuration
├── superball-thrower.service  # Systemd service file
├── install.sh            # Installation script
└── README.md             # This documentation
```

## Dependencies

- **Node.js 16+**: Runtime environment
- **nostr-tools**: NOSTR protocol implementation
- **ws**: WebSocket client for relay connections

## Installation Details

The installation script (`install.sh`) performs the following:

1. **System Requirements Check**: Verifies Node.js and npm installation
2. **Dependency Installation**: Installs required Node.js packages
3. **User Creation**: Creates a dedicated `superball` system user
4. **Directory Setup**: Creates log and configuration directories
5. **Service Installation**: Installs and configures systemd service
6. **Permission Setup**: Secures files with appropriate permissions

## Service Management

### Start/Stop/Restart
```bash
sudo systemctl start superball-thrower
sudo systemctl stop superball-thrower
sudo systemctl restart superball-thrower
```

### Enable/Disable Auto-start
```bash
sudo systemctl enable superball-thrower
sudo systemctl disable superball-thrower
```

### View Status and Logs
```bash
sudo systemctl status superball-thrower
sudo journalctl -u superball-thrower -f
sudo journalctl -u superball-thrower --since "1 hour ago"
```

## Monitoring

### Log Files
- **System Logs**: `journalctl -u superball-thrower`
- **Application Logs**: `/var/log/superball/daemon.log`

### Key Metrics to Monitor
- **Events Processed**: Number of routing events handled
- **Queue Length**: Current number of queued events
- **Relay Connections**: Number of active relay connections
- **Authentication Status**: Relay read/write capabilities

### Health Checks
The daemon logs important events including:
- Startup and shutdown
- Relay connection status
- Event processing statistics
- Error conditions and recovery

## Troubleshooting

### Common Issues

1. **Service Won't Start**
   - Check configuration file syntax: `sudo journalctl -u superball-thrower`
   - Verify private key format (64-character hex string)
   - Ensure relay URLs are valid WebSocket endpoints

2. **No Events Being Processed**
   - Verify relay connections in logs
   - Check if thrower info is being published
   - Confirm private key corresponds to expected public key

3. **Permission Errors**
   - Ensure configuration file is owned by `superball` user
   - Check directory permissions: `/var/log/superball`, `/etc/superball`

4. **Relay Connection Issues**
   - Test relay URLs manually with WebSocket tools
   - Check firewall settings for outbound connections
   - Verify relay authentication requirements

### Debug Mode
Enable verbose logging by editing the service file:
```bash
sudo systemctl edit superball-thrower
```

Add:
```ini
[Service]
Environment=DEBUG=1
```

## Security Considerations

### Private Key Security
- Store private keys securely in the configuration file
- Use proper file permissions (600) for configuration
- Consider using hardware security modules for production

### Network Security
- Use TLS-enabled relay connections (wss://)
- Monitor relay authentication requirements
- Implement firewall rules for outbound connections

### System Security
- Run daemon as dedicated non-privileged user
- Use systemd security features (NoNewPrivileges, etc.)
- Regular security updates for Node.js and dependencies

## Development

### Running in Development Mode
```bash
cd thrower_daemon
npm install
node daemon.js
```

### Configuration for Development
Copy `config.json` to a local file and modify as needed:
```bash
cp config.json config-dev.json
# Edit config-dev.json with your settings
node daemon.js config-dev.json
```

## Maximum Delay Feature

The daemon implements a maximum delay security feature:

- **Default Maximum**: 86460 seconds (1 day + 60 seconds)
- **Purpose**: Prevents attackers from creating routing instructions with excessive delays
- **Validation**: All incoming routing instructions are validated against the configured maximum
- **Configuration**: Set via `maxDelay` field in thrower configuration
- **Publishing**: Maximum delay is published in Thrower Information Documents (SUP-06)

## Contributing

This daemon is part of the Superball project. For contributions:

1. Follow the existing code style and patterns
2. Test thoroughly with multiple relay configurations
3. Update documentation for any new features
4. Ensure backward compatibility with existing configurations

## License

This project follows the same license as the main Superball project.

## Support

For support and questions:
- Check the logs first: `sudo journalctl -u superball-thrower`
- Review this documentation
- Check the main Superball project documentation
- Report issues with detailed logs and configuration (redact private keys)

---

**⚠️ Security Warning**: Always secure your private keys and never share them. The daemon handles sensitive cryptographic operations and should be deployed with appropriate security measures.