# Dogecoin (DOGE) Integration Guide 🐕

**Much Payments! Such Commerce! Very Wow!**

## Overview

Make Post Sell's Dogecoin integration provides fast, low-cost cryptocurrency payments using **Dogecoin Core in pruned mode** - delivering full hot wallet functionality with minimal infrastructure requirements (2.2GB vs 200GB+ blockchain storage).

**Dogecoin Advantages:**

- ✅ **Ultra-low fees** - Perfect for small payments (~$0.001 transaction fees)
- ✅ **Fast confirmations** - 1-minute blocks for quick transaction settlement
- ✅ **Pruned mode support** - Only 2.2GB storage vs 200GB+ full blockchain
- ✅ **Strong community** - Excellent exchange support and liquidity
- ✅ **Proven infrastructure** - Bitcoin-based technology with years of reliability

## Architecture

Label-Based Payment Tracking
----------------------------

Unlike Monero's subaddress system, Dogecoin uses label-based address management for payment isolation:

**Address Structure:**
```
Dogecoin Wallet: make_post_sell_hot_wallet
├── Address D1A2B3... (label: "payment-abc123") → Shop A, Payment #1
├── Address D4C5D6... (label: "payment-def456") → Shop A, Payment #2  
├── Address D7E8F9... (label: "payment-ghi789") → Shop B, Payment #1
└── Address D0G1H2... (label: "payment-jkl012") → Shop B, Payment #2
```

**Benefits:**
- Unique address per payment for perfect isolation
- Label-based tracking for easy payment identification
- Single wallet serving all shops efficiently
- Standard Bitcoin RPC interface compatibility

## Payment Flow

Dogecoin-Specific Processing
----------------------------

**1. Payment Address Generation**
```javascript
// Create unique labeled address for each payment
address = client.getnewaddress(f"payment-{payment.id}")

// Store address details
payment.address = address
payment.coin_type = "DOGE"
payment.shop_id = shop.id
```

**2. Payment Monitoring**
```javascript
// Scan for transactions to specific addresses
transactions = client.listtransactions(
    label="*",        // All transactions
    count=100,        // Recent transactions
    skip=0
)

// Filter for payment-specific transactions
for tx in transactions:
    if tx.address == payment.address and tx.category == "receive":
        process_incoming_transaction(payment, tx)
```

**3. Confirmation Processing**
```javascript
// Check confirmations against requirements
current_height = client.getblockcount()
confirmations = tx.confirmations

if confirmations >= payment.confirmations_required:
    payment.status = CryptoPayment.STATUS_CONFIRMED
    finalize_payment(payment)
    
    // Trigger auto-sweep
    auto_sweep_payment(payment, confirmed_amount)
```

**4. Auto-Sweep Execution**
```javascript
// Immediate sweep to shop's cold wallet
tx_hash = client.sendtoaddress(
    address=payment.shop.cold_wallet_address,
    amount=confirmed_amount - fee_reserve,
    comment=f"Auto-sweep for payment {payment.id}",
    comment_to="",
    subtractfeefromamount=True  // Subtract fee from amount
)

log.sweep_operation(payment, "DOGE auto-sweep successful", tx_hash, swept_amount)
```

## Installation and Setup

### System Requirements

**Resource Usage (Production Measurements):**
- **RAM During Initial Sync**: ~4GB recommended
- **RAM After Sync**: ~200MB active memory usage (158MB RSS)
- **Disk Space**: ~2.2GB for pruned mode (vs 200GB+ for full node)
- **Network**: Good peer connectivity for blockchain sync
- **Sync Time**: 2-4 hours for pruned mode

### Recommended Setup: Pruned Mode ✨

**Minimal blockchain storage** with **full hot wallet functionality**.

#### 1. Install Dogecoin Core
```bash
# Automatic installation with Make
make install-dogecoin
```

This command downloads and installs Dogecoin Core v1.14.6 to `/usr/local/bin`.

#### 2. Configure Pruned Mode
```bash
# Create configuration for pruned node
make dogecoin-config
```

This creates `~/.dogecoin/dogecoin.conf` with:
- Pruned mode (2.2GB storage limit)
- RPC server configuration
- Reliable peer connections
- Hot wallet setup

#### 3. Start & Sync (Much Faster!)
```bash
# Start dogecoin daemon
make dogecoin-node

# Monitor sync progress
make dogecoin-status
```

Initial sync takes ~2-4 hours for pruned mode. The status command shows:
- Current block height vs total headers
- Sync percentage
- When blocks equal headers, sync is complete

#### 4. Configure Make Post Sell
```ini
# Enable Dogecoin payments
app.payments.dogecoin.enabled = False  # Default from development.ini

# Connect to local pruned node
dogecoin.rpc_url = http://127.0.0.1:22555  # Default from development.ini
dogecoin.rpc_user = mps_doge_user          # Default from development.ini
dogecoin.rpc_pass = change_this_password_in_production  # Default from development.ini

# Confirmation settings (risk-based)
# Note: Payment tier thresholds ($10 and $100) are shop settings, not INI settings
dogecoin.confirmations.petty = 2     # < $10: 2 confirmations (default from development.ini)
dogecoin.confirmations.mid = 6       # $10-$100: 6 confirmations (default from development.ini)
dogecoin.confirmations.high = 20     # > $100: 20 confirmations (default from development.ini)

# Fee management
dogecoin.fee_buffer = 0.002          # DOGE kept for transaction fees (reduced from 0.01)
dogecoin.rate_source_url = https://api.coingecko.com/api/v3/simple/price?ids=dogecoin&vs_currencies=usd
```

### Shop-Specific Settings

Each shop can configure payment risk thresholds through the web interface:

- **Mid Tier Threshold**: Default $10.00 (stored as 1000 cents)
- **High Tier Threshold**: Default $100.00 (stored as 10000 cents)
- **Quote Expiry**: Default 3600 seconds (60 minutes)

These thresholds determine which confirmation requirements apply to each payment:

- Payments under the mid threshold use `dogecoin.confirmations.petty` (2 confirmations)
- Payments between mid and high use `dogecoin.confirmations.mid` (6 confirmations)
- Payments over the high threshold use `dogecoin.confirmations.high` (20 confirmations)

**Important**: The $0.64 minimum payment threshold is hardcoded and cannot be changed. This prevents processing payments that would cost more in fees than their value.

## Development Environment

### Quick Start for Developers

**1. Setup Dogecoin Node**
```bash
# Create configuration and start pruned node
make dogecoin-config
make dogecoin-node

# Check sync status
make dogecoin-status
```

**2. Start Payment Processing**
```bash
# Start crypto watcher service
make crypto-watcher

# Or run once for testing
make crypto-watcher-once
```

**3. Start Web Application**
```bash
# Start development server
make serve
```

**Testing and Validation**
```bash
# Run Dogecoin-specific tests
py.test make_post_sell/tests/test_crypto_watcher.py -k "doge or dogecoin"

# Test node connectivity
dogecoin-cli getblockchaininfo
dogecoin-cli getnetworkinfo
dogecoin-cli getwalletinfo
```

## Production Deployment

### Security Configuration

**Node Security:**

Use `make dogecoin-config` to generate a secure configuration file. The generated `dogecoin.conf` includes secure RPC credentials that must be changed for production use.

**Network Security:**
```bash
# Firewall rules (iptables example)
# Only allow local connections to Dogecoin RPC
iptables -A INPUT -p tcp --dport 22555 -s 127.0.0.1 -j ACCEPT
iptables -A INPUT -p tcp --dport 22555 -j REJECT

# Block P2P port from internet (optional, for extra security)
iptables -A INPUT -p tcp --dport 22556 -s 127.0.0.1 -j ACCEPT
iptables -A INPUT -p tcp --dport 22556 -j REJECT
```

**File Permissions:**
```bash
# Secure dogecoin data directory
chmod 700 ~/.dogecoin/
chmod 600 ~/.dogecoin/dogecoin.conf
chmod 600 ~/.dogecoin/wallet.dat

# Run dogecoind as dedicated user (optional)
useradd -r -s /bin/false dogecoin
chown -R dogecoin:dogecoin /home/dogecoin/.dogecoin/
```

### Cold Storage Integration

**Shop Configuration:**

Each shop configures their own cold wallet address through the web interface. The system performs basic format checking but cannot verify the address is accessible - test with small amounts before relying on auto-sweep.

**Auto-Sweep System:**

The system uses perfect accounting to the quote amount - sweeping exactly what the customer paid (including fee buffers). Quotes are calculated in atomic units (koinu) for precision. After confirmation, the full payment amount is swept to cold storage with network fees paid from the balance. Each shop's funds are swept to their configured cold wallet address immediately after confirmation. This approach prevents dust accumulation in the hot wallet.

## Monitoring and Maintenance

### Dogecoin Health Monitoring

**Key Metrics:**
```bash
# Use Make commands for monitoring
make dogecoin-status      # Check sync status and progress
make dogecoin-config      # View/create configuration
make dogecoin-node        # Start pruned node
```

**Automated Health Checks:**

Use `make dogecoin-status` to check node health and sync status. The crypto watcher service monitors payment processing health automatically.

### Log Analysis

**Dogecoin-Specific Log Patterns:**
```bash
# Monitor Dogecoin payment processing
grep "DOGE.*confirmed" logs/crypto_watcher.log

# Check auto-sweep operations
grep "DOGE.*swept to cold storage" logs/crypto_watcher.log

# Monitor RPC connectivity
grep "Dogecoin RPC" logs/crypto_watcher.log

# Payment creation tracking
grep "DOGE.*payment.*created" logs/crypto_watcher.log
```

**Performance Monitoring:**
```bash
# Payment processing times
grep "Payment.*DOGE.*state transition" logs/crypto_watcher.log | \
    awk '{print $1, $2, $NF}' | \
    sort
```

**Error Analysis:**
```bash
# Common Dogecoin error patterns
grep -E "(insufficient.*funds|connection.*refused|wallet.*locked)" logs/crypto_watcher.log

# RPC communication errors
grep "Dogecoin RPC connection error" logs/crypto_watcher.log
```

## Troubleshooting

### Common Issues

**Node Synchronization Problems:**
```bash
# Check if daemon is running
ps aux | grep dogecoind

# Check connection status
make dogecoin-status  # Shows peers and sync status
```

**Wallet Issues:**
```bash
# Wallet managed by dogecoind configuration
# Check status with:
make dogecoin-status
```

**Address and Transaction Issues:**
```bash
# Address and transaction tracking handled by crypto_watcher
# View payment activity in logs:
tail -f logs/crypto_watcher.log | grep DOGE
```

**Recovery Procedures:**

Regular wallet.dat backups are critical. Store backups in secure, offline locations. For emergency sweeps, use `COLD_WALLET_ADDRESS=<address> make sweep-all-doge`.

## Advanced Configuration

### Alternative: Full Node Mode

If maximum decentralization is required, you can run a full node instead of pruned mode. This requires ~200GB+ storage and 8-12 hours for initial synchronization, but provides complete blockchain history and validation.

To run a full node, modify the generated configuration to remove the `prune` setting.

## Production Best Practices

### Security Checklist

**Before Production:**
- [ ] Change default RPC credentials in `dogecoin.conf`
- [ ] Verify firewall rules block external RPC access
- [ ] Test backup and recovery procedures
- [ ] Configure monitoring and alerting
- [ ] Validate cold wallet addresses for all shops
- [ ] Test auto-sweep functionality end-to-end

**Operational Security:**
- [ ] Regular wallet backups (daily automated)
- [ ] Monitor node synchronization status
- [ ] Alert on RPC connection failures
- [ ] Monitor auto-sweep operation success rates
- [ ] Regular security updates for Dogecoin Core

### Monitoring Checklist

**Key Metrics to Track:**
- Node synchronization status (blocks vs headers)
- RPC response times and error rates
- Wallet balance trends and auto-sweep success
- Payment processing times and confirmation rates
- Network connectivity and peer count

**Alert Conditions:**
- Node falls behind in synchronization (>10 blocks)
- RPC service becomes unresponsive
- Auto-sweep operations fail
- Wallet balance exceeds configured thresholds
- Unusual transaction patterns or amounts

## Conclusion

Dogecoin integration in Make Post Sell provides a fast, cost-effective payment solution perfect for small-value transactions and rapid confirmation requirements. The pruned mode operation delivers full hot wallet functionality while minimizing infrastructure overhead.

**Key Benefits for Dogecoin:**

- **Ultra-low costs** - Perfect for micro-payments and small transactions
- **Fast confirmations** - 1-minute blocks for quick customer experience  
- **Minimal infrastructure** - 2.2GB pruned mode vs 200GB+ full blockchain
- **Proven reliability** - Bitcoin-based technology with years of testing
- **Strong ecosystem** - Excellent exchange support and community backing
- **Production-ready** - Comprehensive testing and monitoring capabilities

Much secure! Such payments! Very production! 🐕🚀

For general cryptocurrency system information, see `docs/CRYPTO.rst`. For Monero-specific setup, see `docs/MONERO.rst`.