Skip to content

plan: BQIP-0002 PoW difficulty & mining protocol implementation #33

@AlphaB135

Description

@AlphaB135

Overview

Implement BQIP-0002 PoW difficulty & mining protocol with ASERT difficulty adjustment, hybrid mining support, and Stratum server integration.

Current State Analysis

✅ Already Implemented

  • Block Weight System: BQIP-0002 fully implemented in crates/consensus/src/lib.rs:363-415

    • Weight formula: (base_size * 4) + (signature_count * 384)
    • MAX_BLOCK_WEIGHT: 4,000,000 WU
    • Proper overflow protection and validation
  • ASERT Difficulty: Core implementation in crates/consensus/src/asert.rs

    • Integer fixed-point arithmetic (32.32 format)
    • Burst guard mechanism for rapid difficulty increases
    • Deterministic cross-platform behavior
  • Hybrid PoW Engines: Multi-algorithm support in crates/consensus/src/pow.rs

    • SHA-256d, RandomX, Ethash algorithms
    • Algorithm switching at configurable heights
    • Cached VM for RandomX to prevent DoS
  • Mining Infrastructure: Basic components in crates/node/src/

    • miner.rs: Hybrid mining controller with metrics
    • stratum_server.rs: Stratum V1 server for external miners
    • pool_template.rs: Block template management
    • vardiff.rs: Variable difficulty adjustment

❌ Missing Components

1. ASERT Configuration & Test Vectors

  • No consensus constants defined (T_target, Drift_max, MTP window)
  • Missing test vectors for ASERT calculations
  • No integration with block validation

2. Stratum Security & Protocol

  • Basic Stratum V1 implementation exists but lacks:
    • Authentication mechanisms
    • DoS protection limits
    • Proper share validation
    • Mining template security

3. Mining Pool Integration

  • No pool management logic
  • Missing reward distribution
  • No miner statistics persistence
  • No pool dashboard integration

4. Performance & Monitoring

  • Mining metrics not exposed
  • No performance benchmarks
  • Missing hashrate monitoring
  • No difficulty adjustment feedback

Implementation Plan

Phase 1: ASERT Configuration & Testing (Priority: HIGH)

Files: crates/consensus/src/lib.rs, crates/consensus/src/asert.rs

  1. Define ASERT Constants

    // Add to ConsensusParams
    pub struct AsertParams {
        pub target_block_time: u64,        // 600 seconds (10 min)
        pub half_life: u64,                 // 14,400 seconds (4 hours)
        pub max_drift: f64,                // 0.25 (25% max drift)
        pub mtp_window: u64,               // 11 blocks (Bitcoin standard)
        pub min_difficulty: u32,            // DEVNET_MIN_BITS
        pub max_difficulty: u32,            // DEVNET_MAX_BITS
    }
  2. Create Test Vectors

    • Generate reference ASERT calculations
    • Test difficulty adjustment scenarios
    • Validate burst guard behavior
  3. Integrate with Block Validation

    • Connect ASERT to validate_block() function
    • Add difficulty state tracking
    • Implement retarget logic

Phase 2: Stratum Security Enhancement (Priority: HIGH)

Files: crates/node/src/stratum_server.rs

  1. Add Authentication

    struct StratumAuth {
        username: String,
        password_hash: Option<[u8; 32]>,
        session_id: Uuid,
        authorized_at: Instant,
    }
  2. Implement DoS Protection

    • Rate limiting per connection
    • Maximum share submission rate
    • Connection timeout enforcement
    • Memory usage limits
  3. Enhance Share Validation

    • Proper nonce range checking
    • Algorithm-specific validation
    • Duplicate share detection
    • Share difficulty verification

Phase 3: Mining Pool Management (Priority: MEDIUM)

Files: crates/node/src/pool_*.rs

  1. Pool Manager

    pub struct PoolManager {
        config: PoolConfig,
        miners: DashMap<String, MinerSession>,
        rewards: RewardEngine,
        stats: PoolStats,
    }
  2. Reward Distribution

    • PPS (Pay Per Share) implementation
    • PPLNS (Pay Per Last N Shares) support
    • Pool fee calculation
    • Automatic payout system
  3. Miner Statistics

    • Hashrate tracking per miner
    • Share acceptance/rejection rates
    • Earnings history
    • Performance metrics

Phase 4: Performance & Monitoring (Priority: MEDIUM)

Files: crates/node/src/mining.rs, crates/node/src/metrics.rs

  1. Mining Metrics

    pub struct MiningMetrics {
        total_hashrate: AtomicU64,
        shares_accepted: AtomicU64,
        shares_rejected: AtomicU64,
        blocks_found: AtomicU64,
        difficulty: AtomicU64,
    }
  2. Performance Benchmarks

    • Hashrate benchmarks per algorithm
    • Memory usage profiling
    • Network throughput testing
    • Latency measurements
  3. Monitoring Integration

    • Prometheus metrics export
    • Health check endpoints
    • Alert system integration
    • Dashboard data feeds

Technical Requirements

Security Considerations

  • 51% Attack Resistance: Difficulty adjustment must respond to rapid hashrate changes
  • DoS Protection: Rate limits and memory bounds for Stratum connections
  • Share Validation: Prevent invalid share submissions and spam
  • Pool Security: Secure authentication and authorization

Performance Targets

  • Hashrate: Support > 1 GH/s combined across all algorithms
  • Latency: < 100ms share verification time
  • Memory: < 1GB for full mining operation
  • Throughput: > 1000 shares/second processing capacity

Integration Points

  • Consensus: ASERT must integrate with block validation
  • RPC: Mining status and configuration endpoints
  • GUI: Mining dashboard integration
  • Storage: Pool data and statistics persistence

Testing Strategy

Unit Tests

  • ASERT calculation accuracy
  • Block weight validation
  • Share verification logic
  • Difficulty adjustment scenarios

Integration Tests

  • End-to-end mining workflow
  • Stratum server functionality
  • Pool management operations
  • Multi-algorithm switching

Performance Tests

  • Hashrate benchmarks
  • Memory usage profiling
  • Network stress testing
  • Concurrent mining simulation

Success Criteria

Functional Requirements

  • ASERT difficulty adjustment working correctly
  • Hybrid mining with 3+ algorithms
  • Secure Stratum server with authentication
  • Functional mining pool with rewards
  • Complete monitoring and metrics

Performance Requirements

  • > 500 MH/s per algorithm sustained
  • < 50ms average share verification
  • < 512MB memory footprint
  • 99.9% uptime under load

Security Requirements

  • DoS protection active and tested
  • Authentication working correctly
  • Share validation preventing exploits
  • Pool funds secure and auditable

Risks & Mitigations

Technical Risks

  • ASERT Implementation: Complex fixed-point math
    • Mitigation: Extensive test vectors and reference implementation
  • RandomX Performance: CPU-intensive algorithm
    • Mitigation: Proper caching and thread management
  • Stratum Security: Public-facing server
    • Mitigation: Rate limiting and authentication

Integration Risks

  • Consensus Changes: Difficulty adjustment affects validation
    • Mitigation: Careful testing and gradual rollout
  • Pool Economics: Reward distribution bugs
    • Mitigation: Formal verification and simulation

Timeline Estimate

  • Phase 1: 2-3 days (ASERT configuration and testing)
  • Phase 2: 2-3 days (Stratum security)
  • Phase 3: 3-4 days (Pool management)
  • Phase 4: 2-3 days (Performance and monitoring)

Total: 9-13 days for complete implementation

Next Steps

  1. Start with Phase 1 (ASERT configuration) - highest priority
  2. Implement test vectors before integration
  3. Focus on security before performance
  4. Add monitoring throughout the process

This plan provides a comprehensive roadmap for implementing BQIP-0002 with proper security, performance, and monitoring considerations.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions