=====================================
Monero (XMR) Integration Guide
=====================================

**Privacy-First Cryptocurrency Payment Processing**

Overview
========

Make Post Sell's Monero integration provides a comprehensive multi-tenant cryptocurrency payment system that enables any shop to accept XMR payments with complete financial isolation, automatic fund management, and privacy-focused transaction processing.

**Monero Advantages:**

- ✅ **Built-in privacy** - All transactions are private by default
- ✅ **Subaddress system** - Perfect payment isolation per customer
- ✅ **Remote node support** - No blockchain storage requirements
- ✅ **Mature infrastructure** - Comprehensive RPC API and wallet tools
- ✅ **Multi-tenant ready** - Account-based financial isolation

Architecture
============

Multi-Tenant Account System
---------------------------

Make Post Sell implements a sophisticated account-based isolation system where each shop gets its own dedicated Monero account within a single wallet:

**Account Structure:**
::

    Wallet: make_post_sell_master
    ├── Account 0: Shop A (Digital Downloads)
    │   ├── Subaddress 0: Primary (sweep destination)
    │   ├── Subaddress 1: Payment #abc123
    │   └── Subaddress 2: Payment #def456
    ├── Account 1: Shop B (Physical Goods)
    │   ├── Subaddress 0: Primary (sweep destination)
    │   ├── Subaddress 1: Payment #ghi789
    │   └── Subaddress 2: Payment #jkl012
    └── Account N: Shop N...

**Benefits:**
- Complete financial isolation between shops
- Simplified wallet management (single RPC service)
- Automatic account creation when shops enable Monero
- Subaddress generation for unique payment addresses

Payment Flow
============

Monero-Specific Processing
--------------------------

**1. Shop Onboarding**
::

    # When shop enables Monero payments:
    
    # Create dedicated account
    account_label = f"mps-shop-{shop.uuid_str}"
    result = client._call("create_account", {"label": account_label})
    account_index = result.get("account_index")
    
    # Tag account for identification
    client._call("tag_accounts", {
        "tag": shop.name, 
        "accounts": [account_index]
    })
    
    # Store account index for future use
    processor.wallet_label = str(account_index)

**2. Payment Address Generation**
::

    # Create unique subaddress for each payment
    address, subaddr_index = client.create_subaddress(
        account_index=shop.account_index,
        label=f"payment-{payment.id}"
    )
    
    # Store subaddress details
    payment.address = address
    payment.subaddress_index = subaddr_index
    payment.account_index = shop.account_index

**3. Payment Monitoring**
::

    # Scan specific subaddresses for incoming transfers
    transfers = client.get_transfers_for_subaddr(
        account_index=payment.account_index,
        subaddr_indices=[payment.subaddress_index]
    )
    
    # Process incoming transfers
    for transfer in transfers.get('in', []):
        if transfer['subaddr_index']['minor'] == payment.subaddress_index:
            process_incoming_transfer(payment, transfer)

**4. Confirmation Processing**
::

    # Check confirmations against requirements
    wallet_height = client.get_height()
    confirmations = wallet_height - transfer['height']
    
    if confirmations >= payment.confirmations_required:
        payment.status = CryptoPayment.STATUS_CONFIRMED
        finalize_payment(payment)
        
        # Trigger auto-sweep
        auto_sweep_payment(payment, confirmed_amount)

Installation and Setup
======================

System Requirements
-------------------

**Resource Usage (Production Measurements):**
- **With Remote Node**: ~512MB RAM, ~11MB active memory usage
- **With Local Node**: ~2GB RAM for monerod + wallet RPC
- **Disk Space**: None for remote node, ~150GB for full local blockchain
- **Network**: Stable internet connection for RPC communication

Monero Node Requirements
------------------------

**Option 1: Remote Node (Recommended for Development)**
::

    # No blockchain download required
    # Uses public Monero nodes for blockchain data
    # Wallet-only operation mode
    
    # Start wallet RPC with remote node
    monero-wallet-rpc \
        --wallet-file=data/mps-wallet \
        --password-file=data/wallet-password.txt \
        --rpc-bind-ip=127.0.0.1 \
        --rpc-bind-port=18083 \
        --daemon-address=opennode.xmr-tw.org:18089 \
        --trusted-daemon \
        --log-level=1

**Option 2: Local Node (Production)**
::

    # Full blockchain synchronization (~150GB)
    # Maximum privacy and reliability
    # Independent operation
    
    # Start local Monero daemon
    monerod \
        --data-dir=data/monero-blockchain \
        --rpc-bind-ip=127.0.0.1 \
        --rpc-bind-port=18081 \
        --log-level=1
    
    # Start wallet RPC with local daemon
    monero-wallet-rpc \
        --wallet-file=data/mps-wallet \
        --password-file=data/wallet-password.txt \
        --rpc-bind-ip=127.0.0.1 \
        --rpc-bind-port=18083 \
        --daemon-address=127.0.0.1:18081 \
        --trusted-daemon \
        --log-level=1

Wallet Creation
---------------

**Initial Wallet Setup:**
::

    # Create new wallet (first time only)
    monero-wallet-cli \
        --generate-new-wallet=data/mps-wallet \
        --password-file=data/wallet-password.txt
    
    # IMPORTANT: Save the 25-word mnemonic seed!
    # This is your only recovery method for the wallet

**Configuration Setup:**
::

    # Enable Monero payments in configuration
    app.payments.monero.enabled = False  # Default from development.ini
    
    # Wallet RPC connection (development.ini defaults)
    monero.rpc_url = http://127.0.0.1:18083/json_rpc
    monero.rpc_user = test_user          # Default from development.ini
    monero.rpc_pass = test_pass          # Default from development.ini
    monero.account_index = 0             # Default account index
    
    # Confirmation thresholds based on risk
    # Note: Payment tier thresholds ($10 and $100) are shop settings
    monero.confirmations.petty = 2       # Under $10 (default from development.ini)
    monero.confirmations.mid = 10        # $10-$100 (default from development.ini)
    monero.confirmations.high = 20       # Over $100 (default from development.ini)
    
    # Quote and rate settings
    monero.quote_expiry_seconds = 900    # 15 minutes (default from development.ini)
    monero.rate_source_url = https://api.coingecko.com/api/v3/simple/price?ids=monero&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 ``monero.confirmations.petty`` (2 confirmations)
- Payments between mid and high use ``monero.confirmations.mid`` (10 confirmations)
- Payments over the high threshold use ``monero.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. Start Monero Wallet (Remote Node)**
::

    # Quick development setup with remote node
    make monero-wallet-remote
    
    # Or with authentication for testing
    make monero-wallet-remote-auth

**2. Start Payment Processing**
::

    # Start crypto watcher service
    make crypto-watcher
    
    # Or run once for testing
    make crypto-watcher-once

**3. Start Web Application**
::

    # Start development server
    make serve

**Testing and Validation**
::

    # Run Monero-specific tests
    py.test make_post_sell/tests/test_crypto_watcher.py -k "xmr or monero"
    
    # Test wallet connectivity using Make commands
    make test-monero-connection

Production Deployment
=====================

Security Configuration
-----------------------

**Wallet Security:**
::

    # Production wallet RPC with authentication
    monero-wallet-rpc \
        --wallet-file=/secure/path/mps-wallet \
        --password-file=/secure/path/wallet-password.txt \
        --rpc-bind-ip=127.0.0.1 \
        --rpc-bind-port=18083 \
        --rpc-login=secure_user:very_secure_password \
        --daemon-address=your.trusted.node:18089 \
        --trusted-daemon \
        --log-level=1

**Network Security:**
::

    # Firewall rules (iptables example)
    # Only allow local connections to wallet RPC
    iptables -A INPUT -p tcp --dport 18083 -s 127.0.0.1 -j ACCEPT
    iptables -A INPUT -p tcp --dport 18083 -j REJECT
    
    # If using local daemon, secure it similarly
    iptables -A INPUT -p tcp --dport 18081 -s 127.0.0.1 -j ACCEPT
    iptables -A INPUT -p tcp --dport 18081 -j REJECT

**File Permissions:**
::

    # Secure wallet files and directories
    chmod 700 /secure/path/
    chmod 600 /secure/path/mps-wallet*
    chmod 600 /secure/path/wallet-password.txt
    
    # Run wallet RPC as dedicated user
    useradd -r -s /bin/false monero-wallet
    chown monero-wallet:monero-wallet /secure/path/mps-wallet*

Cold Storage Integration
------------------------

**Shop Configuration:**

Each shop must configure their own cold wallet address for automatic sweep destinations through the web interface. The system performs basic format checking but cannot verify the address is accessible - ensure you control the wallet before configuring.

**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 (piconero) for precision. After confirmation, the full payment amount is swept to cold storage with network fees deducted from the transfer. Each shop's funds are isolated in separate accounts. This approach prevents dust accumulation since exact amounts are swept.

Monitoring and Maintenance
==========================

Wallet Health Monitoring
-------------------------

**Key Metrics:**
::

    # Use Make Post Sell monitoring commands
    make monero-transactions  # View recent transactions
    make crypto-watcher       # Monitor payment processing


Log Analysis
------------

**Monero-Specific Log Patterns:**
::

    # Monitor Monero payment processing
    grep "XMR.*confirmed" logs/crypto_watcher.log
    
    # Check auto-sweep operations
    grep "XMR.*swept to cold storage" logs/crypto_watcher.log
    
    # Monitor wallet connectivity
    grep "Monero RPC" logs/crypto_watcher.log
    
    # Account creation tracking
    grep "account.*created.*shop" logs/crypto_watcher.log

**Performance Monitoring:**
::

    # Payment processing time analysis
    grep "Payment.*XMR.*state transition" logs/crypto_watcher.log | \
        awk '{print $1, $2, $NF}' | \
        sort

**Error Analysis:**
::

    # Common Monero error patterns
    grep -E "(wallet.*locked|daemon.*not.*reachable|insufficient.*balance)" logs/crypto_watcher.log
    
    # RPC communication errors
    grep "Monero RPC connection error" logs/crypto_watcher.log

Troubleshooting
===============

Common Issues
-------------

**Wallet Synchronization Problems:**

- Check that monero-wallet-rpc is running
- Verify remote node connectivity
- Ensure wallet file is accessible

**Account/Subaddress Issues:**

- Ensure shop account indices are properly assigned
- Check that account creation succeeded during setup
- Verify cold wallet addresses are configured

**Payment Tracking Issues:**

- Use ``make monero-transactions`` to view recent transfers
- Check crypto_watcher logs for payment detection
- Verify subaddress labels match payment IDs

**Recovery Procedures:**

Wallet recovery requires the 25-word mnemonic seed saved during wallet creation. Regular wallet file backups are critical. Store backups in secure, offline locations. For emergency sweeps to cold storage, use ``COLD_WALLET_ADDRESS=<address> make sweep-all``.

Advanced Configuration
======================

Performance Tuning
-------------------

**Wallet RPC Optimization:**
::

    # Increase RPC timeout for large operations
    monero-wallet-rpc \
        --wallet-file=data/mps-wallet \
        --rpc-bind-port=18083 \
        --daemon-address=remote.node:18089 \
        --trusted-daemon \
        --max-concurrency=4 \
        --log-level=1

**Memory Management:**

For high-volume shops, monero-wallet-rpc memory usage is minimal with remote nodes. The wallet only maintains account and subaddress data, not full transaction history.


Scaling Considerations
----------------------

**Single Wallet Limitation:**

The Monero wallet architecture requires all shops to share a single wallet file with unique account indices. This design:

- Prevents multi-node setups (account indices would mismatch)
- Makes horizontal scaling impossible for the wallet layer
- Requires careful backup strategies since all shops depend on one wallet

**Scaling Options:**

- Vertical scaling of the single wallet RPC node
- Multiple daemon nodes for blockchain redundancy
- Database replication for payment tracking
- CDN/caching for the web application layer

Conclusion
==========

Monero integration in Make Post Sell provides a robust, privacy-focused payment solution that scales from single-shop installations to large multi-tenant deployments. The account-based isolation system ensures complete financial separation while maintaining operational efficiency through shared infrastructure.

The comprehensive monitoring, automatic fund management, and recovery procedures make this a production-ready solution for businesses requiring privacy-focused cryptocurrency payments with enterprise-grade reliability.

**Key Benefits for Monero:**

- **Privacy-first design** - All transactions are private by default
- **Perfect isolation** - Subaddress system ensures payment separation  
- **Scalable architecture** - Single wallet serving unlimited shops
- **Remote node support** - No blockchain storage requirements
- **Comprehensive monitoring** - Full payment lifecycle tracking
- **Automatic fund management** - Immediate sweep to cold storage
- **Production-tested** - Extensive test coverage and real-world validation

For general cryptocurrency system information, see ``docs/CRYPTO.rst``. For Dogecoin-specific setup, see ``docs/DOGECOIN.md``.